package com.genexususa.eo.bing.connection;

import com.genexususa.eo.bing.ReportManagementServiceClasses.*;
import com.genexususa.eo.bing.data.CustomReportRequest;
import com.genexususa.eo.bing.data.Info;
import org.apache.axis.message.SOAPHeader;

import javax.xml.rpc.ServiceException;
import javax.xml.soap.SOAPHeaderElement;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: Emiliano Martinez
 * Date: 1/9/14
 * Time: 2:00 PM
 * To change this template use File | Settings | File Templates.
 */
public class ReportManager {

    private static java.lang.String _namespace = null;
    private static BasicHttpBinding_IReportingServiceStub _service = null;

    public ReportManager(){

    }

    public void getAllReportForCustomers(String customerAccounts, String location, String date){

        getCampaignPerformanceReport(customerAccounts, location, date);
        getAdGroupPerformanceReport(customerAccounts, location, date);
        getAdPerformanceReport(customerAccounts, location, date);
        getKeywordPerformanceReports(customerAccounts, location, date);
        //getAdExtensionPerformanceReport(customerAccounts, location, date);
        //getConversionPerformanceReport(customerAccounts, location, date);

    }


    public void getKeywordPerformanceReport(Long customerAccountId, String locationFile, String date){

        /*IReportingService reportingService = null;
        ReportingServiceLocator reportingServiceLocator = null; */
        BasicHttpBinding_IReportingServiceStub stub = null;

        try
        {


            HashMap<String, String> properties = Info.getBingProperties();
            String namespace = properties.get("reportingNamespace");
            String url = properties.get("reportingURL");
            String userName = properties.get("username");
            String password = properties.get("password");
            String developerToken = properties.get("developerToken");
            String customerId = properties.get("customerId");
            String applicationToken = properties.get("applicationToken");

            Long wait = Long.parseLong(properties.get("waitForDownload"));

            ReportingServiceLocator locator = new ReportingServiceLocator();
            locator.setBasicHttpBinding_IReportingServiceEndpointAddress(url);
            namespace = locator.getServiceName().getNamespaceURI();
            stub = (BasicHttpBinding_IReportingServiceStub) locator.getBasicHttpBinding_IReportingService();

            stub.clearHeaders();

            stub.setHeader(namespace, "UserName", userName);
            stub.setHeader(namespace, "Password", password);
            stub.setHeader(namespace, "DeveloperToken", developerToken);
            stub.setHeader(namespace, "CustomerId", customerId);
            stub.setHeader(namespace, "CustomerAccountId", customerAccountId);
           // stub.setHeader(namespace, "ApplicationToken", applicationToken);

            KeywordPerformanceReportRequest report = new KeywordPerformanceReportRequest();

            report.setFormat(ReportFormat.Xml);

            report.setReportName("Keywords performance report #" + date);
            report.setReturnOnlyCompleteData(false);
            report.setAggregation(ReportAggregation.Daily);

            report.setScope(new AccountThroughAdGroupReportScope());
            report.getScope().setAccountIds(new long[]{customerAccountId});
            report.getScope().setAdGroups(null);
            report.setTime(new ReportTime());



            String[] dateSplitted = date.split("-");


            report.getTime().setCustomDateRangeStart(new Date());
            report.getTime().getCustomDateRangeStart().setMonth(Integer.parseInt(dateSplitted[1]));
            report.getTime().getCustomDateRangeStart().setDay(Integer.parseInt(dateSplitted[2]));
            report.getTime().getCustomDateRangeStart().setYear(Integer.parseInt(dateSplitted[0]));
            report.getTime().setCustomDateRangeEnd(new Date());
            report.getTime().getCustomDateRangeEnd().setMonth(Integer.parseInt(dateSplitted[1]));
            report.getTime().getCustomDateRangeEnd().setDay(Integer.parseInt(dateSplitted[2]));
            report.getTime().getCustomDateRangeEnd().setYear(Integer.parseInt(dateSplitted[0]));



            report.setColumns(new KeywordPerformanceReportColumn[] {
                    KeywordPerformanceReportColumn.AccountId,
                    KeywordPerformanceReportColumn.AccountName,
                    KeywordPerformanceReportColumn.AccountNumber,
                    KeywordPerformanceReportColumn.AccountStatus,
                    KeywordPerformanceReportColumn.AdDistribution,
                    KeywordPerformanceReportColumn.AdGroupId,
                    KeywordPerformanceReportColumn.AdGroupName,
                    KeywordPerformanceReportColumn.AdGroupStatus,
                    KeywordPerformanceReportColumn.AdId,
                    KeywordPerformanceReportColumn.AdType,
                    KeywordPerformanceReportColumn.AverageCpc,
                    KeywordPerformanceReportColumn.AverageCpm,
                    KeywordPerformanceReportColumn.AveragePosition,
                    KeywordPerformanceReportColumn.BidMatchType,
                    KeywordPerformanceReportColumn.CampaignId,
                    KeywordPerformanceReportColumn.CampaignName,
                    KeywordPerformanceReportColumn.CampaignStatus,
                    KeywordPerformanceReportColumn.Clicks,
                    KeywordPerformanceReportColumn.ConversionRate,
                    KeywordPerformanceReportColumn.Conversions,
                    KeywordPerformanceReportColumn.CostPerConversion,
                    KeywordPerformanceReportColumn.Ctr,
                    KeywordPerformanceReportColumn.CurrencyCode,
                    KeywordPerformanceReportColumn.CurrentMaxCpc,
                    KeywordPerformanceReportColumn.DeliveredMatchType,
                    KeywordPerformanceReportColumn.DestinationUrl,
                    KeywordPerformanceReportColumn.DeviceType,
                    KeywordPerformanceReportColumn.Impressions,
                    KeywordPerformanceReportColumn.Keyword,
                    KeywordPerformanceReportColumn.KeywordId,
                    //KeywordPerformanceReportColumn.KeywordMatchTypeId,
                    KeywordPerformanceReportColumn.KeywordRelevance,
                    KeywordPerformanceReportColumn.KeywordStatus,
                    KeywordPerformanceReportColumn.LandingPageRelevance,
                    KeywordPerformanceReportColumn.LandingPageUserExperience,
                    KeywordPerformanceReportColumn.Language,
                    KeywordPerformanceReportColumn.Network,
                    KeywordPerformanceReportColumn.PricingModel,
                    KeywordPerformanceReportColumn.QualityImpact,
                    KeywordPerformanceReportColumn.QualityScore,
                    KeywordPerformanceReportColumn.Spend,
                    KeywordPerformanceReportColumn.TimePeriod,
                    KeywordPerformanceReportColumn.TopVsOther
            });


            //report.setMaxRows(10000);


            SubmitGenerateReportRequest request = new SubmitGenerateReportRequest();

            request.setReportRequest(report);

            String reportRequestId = stub.submitGenerateReport(request).getReportRequestId();

            System.out.println("Report Request ID: " + reportRequestId + "\n");

            ReportRequestStatus reportRequestStatus = null;

            for (int i = 0; i < 10; i++)
            {
                try {Thread.sleep(wait);}
                catch (InterruptedException ignore) {}


                PollGenerateReportRequest pollRequest = new PollGenerateReportRequest();

                pollRequest.setReportRequestId(reportRequestId);

                reportRequestStatus = stub.pollGenerateReport(pollRequest).getReportRequestStatus();

                System.out.printf("Report Request Status: %s\n", reportRequestStatus);

                if (reportRequestStatus.getStatus() == ReportRequestStatusType.Success ||
                        reportRequestStatus.getStatus() == ReportRequestStatusType.Error)
                {
                    break;
                }
            }

            if (reportRequestStatus != null)
            {
                if (reportRequestStatus.getStatus() == ReportRequestStatusType.Success)
                {
                    java.lang.String reportDownloadUrl = reportRequestStatus.getReportDownloadUrl();
                    System.out.printf("Downloading from %s.\n", reportDownloadUrl);
                    DownloadReport(reportDownloadUrl, locationFile);
                    System.out.printf("The report was written to %s.\n", locationFile);
                }
                else if (reportRequestStatus.getStatus() == ReportRequestStatusType.Error)
                {
                    System.out.println("The request failed. Try requesting the report " +
                            "later.\nIf the request continues to fail, contact support.");
                }
                else  // Pending
                {
                    System.out.println("The request is taking longer than expected.");
                    System.out.printf("Save the report ID (%s) and try again later.", reportRequestId);
                }
            }




        } catch (AdApiFaultDetail adApiFaultDetail) {
            adApiFaultDetail.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (RemoteException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (ServiceException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

    }

    public void getKeywordPerformanceReports(String customerAccounts, String location, String date){
        BasicHttpBinding_IReportingServiceStub stub = null;

        HashMap<String, CustomReportRequest> requests = new HashMap<String, CustomReportRequest>();

        try{
            String[] customerAccountArray = customerAccounts.split(";");

            HashMap<String, String> properties = Info.getBingProperties();
            String namespace = properties.get("reportingNamespace");
            String url = properties.get("reportingURL");
            String userName = properties.get("username");
            String password = properties.get("password");
            String developerToken = properties.get("developerToken");
            String customerId = properties.get("customerId");
            String applicationToken = properties.get("applicationToken");
            int retries = Integer.parseInt(properties.get("retries"));

            Long wait = Long.parseLong(properties.get("waitForDownload"));


            for (String customerAccount: customerAccountArray){

                ReportingServiceLocator locator = new ReportingServiceLocator();
                locator.setBasicHttpBinding_IReportingServiceEndpointAddress(url);
                namespace = locator.getServiceName().getNamespaceURI();
                stub = (BasicHttpBinding_IReportingServiceStub) locator.getBasicHttpBinding_IReportingService();

                CustomReportRequest rr = new CustomReportRequest();

                stub.clearHeaders();

                stub.setHeader(namespace, "UserName", userName);
                stub.setHeader(namespace, "Password", password);
                stub.setHeader(namespace, "DeveloperToken", developerToken);
                stub.setHeader(namespace, "CustomerId", customerId);
                stub.setHeader(namespace, "CustomerAccountId", Long.parseLong(customerAccount));
                stub.setHeader(namespace, "ApplicationToken", applicationToken);


                rr.setStub(stub);

                KeywordPerformanceReportRequest report = new KeywordPerformanceReportRequest();

                report.setFormat(ReportFormat.Xml);

                report.setReportName("Keywords performance report #" + date);
                report.setReturnOnlyCompleteData(false);
                report.setAggregation(ReportAggregation.Daily);

                report.setScope(new AccountThroughAdGroupReportScope());
                report.getScope().setAccountIds(new long[]{Long.parseLong(customerAccount)});
                report.getScope().setAdGroups(null);
                report.setTime(new ReportTime());



                String[] dateSplitted = date.split("-");


                report.getTime().setCustomDateRangeStart(new Date());
                report.getTime().getCustomDateRangeStart().setMonth(Integer.parseInt(dateSplitted[1]));
                report.getTime().getCustomDateRangeStart().setDay(Integer.parseInt(dateSplitted[2]));
                report.getTime().getCustomDateRangeStart().setYear(Integer.parseInt(dateSplitted[0]));
                report.getTime().setCustomDateRangeEnd(new Date());
                report.getTime().getCustomDateRangeEnd().setMonth(Integer.parseInt(dateSplitted[1]));
                report.getTime().getCustomDateRangeEnd().setDay(Integer.parseInt(dateSplitted[2]));
                report.getTime().getCustomDateRangeEnd().setYear(Integer.parseInt(dateSplitted[0]));


                report.setColumns(new KeywordPerformanceReportColumn[] {
                        KeywordPerformanceReportColumn.AdGroupId,
                        KeywordPerformanceReportColumn.AdId,
                        KeywordPerformanceReportColumn.AveragePosition,
                        KeywordPerformanceReportColumn.CampaignId,
                        KeywordPerformanceReportColumn.Clicks,
                        KeywordPerformanceReportColumn.Conversions,
                        KeywordPerformanceReportColumn.Impressions,
                        KeywordPerformanceReportColumn.KeywordId,
                        KeywordPerformanceReportColumn.Spend
                });

                SubmitGenerateReportRequest request = new SubmitGenerateReportRequest();

                request.setReportRequest(report);

                String reportRequestId = stub.submitGenerateReport(request).getReportRequestId();

                rr.setReportRequestId(reportRequestId);

                requests.put(customerAccount, rr);

            }

            ReportRequestStatus reportRequestStatus = null;

            int finished = 0;

            for (int i = 0; i < retries && finished < requests.size(); i++)
            {

                try {Thread.sleep(wait);}
                catch (InterruptedException ignore) {}

                for(Map.Entry<String, CustomReportRequest> crr : requests.entrySet()){

                    PollGenerateReportRequest pollRequest = new PollGenerateReportRequest();

                    pollRequest.setReportRequestId(crr.getValue().getReportRequestId());

                    reportRequestStatus = stub.pollGenerateReport(pollRequest).getReportRequestStatus();

                    System.out.printf("Report Request Status: %s\n", reportRequestStatus);

                    if (reportRequestStatus.getStatus() == ReportRequestStatusType.Success ||
                            reportRequestStatus.getStatus() == ReportRequestStatusType.Error)
                    {
                        crr.getValue().setStatus(reportRequestStatus);
                        crr.getValue().setFinished(true);

                        //break;
                    }


                    if (crr.getValue().isFinished()){

                        if (crr.getValue().getStatus() != null)
                        {
                            if (crr.getValue().getStatus().getStatus() == ReportRequestStatusType.Success)
                            {
                                java.lang.String reportDownloadUrl = crr.getValue().getStatus().getReportDownloadUrl();

                                File locationDir = new File(location + File.separator + crr.getKey() + "-" + date);

                                if (!locationDir.exists())
                                    locationDir.mkdir();

                                System.out.printf("Downloading from %s.\n", reportDownloadUrl);
                                DownloadReport(reportDownloadUrl, location + File.separator + crr.getKey() + "-" + date + File.separator  + "keywordPerformanceReport_" + date + ".zip");
                                System.out.printf("The report was written to %s.\n",location + File.separator + crr.getKey() + "-" + date + File.separator  +  "keywordPerformanceReport_" + date + ".zip");
                                finished++;
                            }
                            else if (reportRequestStatus.getStatus() == ReportRequestStatusType.Error)
                            {
                                System.out.println("The request failed. Try requesting the report " +
                                        "later.\nIf the request continues to fail, contact support.");
                            }
                            else  // Pending
                            {
                                System.out.println("The request is taking longer than expected.");
                                System.out.printf("Save the report ID (%s) and try again later.", crr.getValue().getReportRequestId());
                            }
                        }
                    }
                }
            }

        } catch (AdApiFaultDetail adApiFaultDetail) {
            adApiFaultDetail.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (RemoteException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (ServiceException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

    public void getCampaignPerformanceReport(String customerAccounts, String location, String date){
        BasicHttpBinding_IReportingServiceStub stub = null;

        HashMap<String, CustomReportRequest> requests = new HashMap<String, CustomReportRequest>();

        try{
            String[] customerAccountArray = customerAccounts.split(";");

            HashMap<String, String> properties = Info.getBingProperties();
            String namespace = properties.get("reportingNamespace");
            String url = properties.get("reportingURL");
            String userName = properties.get("username");
            String password = properties.get("password");
            String developerToken = properties.get("developerToken");
            String customerId = properties.get("customerId");
            String applicationToken = properties.get("applicationToken");
            int retries = Integer.parseInt(properties.get("retries"));

            Long wait = Long.parseLong(properties.get("waitForDownload"));


            for (String customerAccount: customerAccountArray){

                ReportingServiceLocator locator = new ReportingServiceLocator();
                locator.setBasicHttpBinding_IReportingServiceEndpointAddress(url);
                namespace = locator.getServiceName().getNamespaceURI();
                stub = (BasicHttpBinding_IReportingServiceStub) locator.getBasicHttpBinding_IReportingService();

                CustomReportRequest rr = new CustomReportRequest();

                stub.clearHeaders();

                stub.setHeader(namespace, "UserName", userName);
                stub.setHeader(namespace, "Password", password);
                stub.setHeader(namespace, "DeveloperToken", developerToken);
                stub.setHeader(namespace, "CustomerId", customerId);
                stub.setHeader(namespace, "CustomerAccountId", Long.parseLong(customerAccount));
                stub.setHeader(namespace, "ApplicationToken", applicationToken);


                rr.setStub(stub);

                CampaignPerformanceReportRequest report = new CampaignPerformanceReportRequest();

                report.setFormat(ReportFormat.Xml);

                report.setReportName("Campaign performance report #" + date);
                report.setReturnOnlyCompleteData(false);
                report.setAggregation(ReportAggregation.Daily);


                report.setScope(new AccountThroughCampaignReportScope());
                report.getScope().setAccountIds(new long[]{Long.parseLong(customerAccount)});
                report.getScope().setCampaigns(null);
                report.setTime(new ReportTime());



                String[] dateSplitted = date.split("-");


                report.getTime().setCustomDateRangeStart(new Date());
                report.getTime().getCustomDateRangeStart().setMonth(Integer.parseInt(dateSplitted[1]));
                report.getTime().getCustomDateRangeStart().setDay(Integer.parseInt(dateSplitted[2]));
                report.getTime().getCustomDateRangeStart().setYear(Integer.parseInt(dateSplitted[0]));
                report.getTime().setCustomDateRangeEnd(new Date());
                report.getTime().getCustomDateRangeEnd().setMonth(Integer.parseInt(dateSplitted[1]));
                report.getTime().getCustomDateRangeEnd().setDay(Integer.parseInt(dateSplitted[2]));
                report.getTime().getCustomDateRangeEnd().setYear(Integer.parseInt(dateSplitted[0]));




                report.setColumns(new CampaignPerformanceReportColumn[]{
                        CampaignPerformanceReportColumn.AveragePosition,
                        CampaignPerformanceReportColumn.CampaignId,
                        CampaignPerformanceReportColumn.Clicks,
                        CampaignPerformanceReportColumn.ClickCalls,
                        CampaignPerformanceReportColumn.Conversions,
                        CampaignPerformanceReportColumn.Impressions,
                        CampaignPerformanceReportColumn.Spend,
                        CampaignPerformanceReportColumn.DeviceType
                });

                SubmitGenerateReportRequest request = new SubmitGenerateReportRequest();

                request.setReportRequest(report);

                String reportRequestId = stub.submitGenerateReport(request).getReportRequestId();

                rr.setReportRequestId(reportRequestId);

                System.out.println("Report Request ID: " + reportRequestId);

                requests.put(customerAccount, rr);


            }


            ReportRequestStatus reportRequestStatus = null;

            int finished = 0;

            for (int i = 0; i < retries && finished < requests.size(); i++)
            {

                try {Thread.sleep(wait);}
                catch (InterruptedException ignore) {}

                for(Map.Entry<String, CustomReportRequest> crr : requests.entrySet()){

                    //stub = crr.getValue().getStub();


                    PollGenerateReportRequest pollRequest = new PollGenerateReportRequest();

                    pollRequest.setReportRequestId(crr.getValue().getReportRequestId());

                    reportRequestStatus = stub.pollGenerateReport(pollRequest).getReportRequestStatus();

                    System.out.printf("Report Request Status: %s\n", reportRequestStatus);

                    if (reportRequestStatus.getStatus() == ReportRequestStatusType.Success ||
                            reportRequestStatus.getStatus() == ReportRequestStatusType.Error)
                    {
                        crr.getValue().setStatus(reportRequestStatus);
                        crr.getValue().setFinished(true);

                        //break;
                    }


                    if (crr.getValue().isFinished()){

                        if (crr.getValue().getStatus() != null)
                        {
                            if (crr.getValue().getStatus().getStatus() == ReportRequestStatusType.Success)
                            {
                                java.lang.String reportDownloadUrl = crr.getValue().getStatus().getReportDownloadUrl();

                                File locationDir = new File(location + File.separator + crr.getKey() + "-" + date);

                                if (!locationDir.exists())
                                    locationDir.mkdir();

                                System.out.printf("Downloading from %s.\n", reportDownloadUrl);
                                DownloadReport(reportDownloadUrl, location + File.separator + crr.getKey() + "-" + date + File.separator + "campaignReport_" + date + ".zip");
                                System.out.printf("The report was written to %s.\n", location + File.separator + crr.getKey() + "-" + date + File.separator + "campaignReport_" + date + ".zip");
                                finished++;
                            }
                            else if (reportRequestStatus.getStatus() == ReportRequestStatusType.Error)
                            {
                                System.out.println("The request failed. Try requesting the report " +
                                        "later.\nIf the request continues to fail, contact support.");
                            }
                            else  // Pending
                            {
                                System.out.println("The request is taking longer than expected.");
                                System.out.printf("Save the report ID (%s) and try again later.", crr.getValue().getReportRequestId());
                            }
                        }
                    }
                }
            }





        } catch (AdApiFaultDetail adApiFaultDetail) {
            adApiFaultDetail.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (RemoteException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (ServiceException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

    }

    public void getAdGroupPerformanceReport(String customerAccounts, String location, String date){
        BasicHttpBinding_IReportingServiceStub stub = null;

        HashMap<String, CustomReportRequest> requests = new HashMap<String, CustomReportRequest>();

        try{
            String[] customerAccountArray = customerAccounts.split(";");

            HashMap<String, String> properties = Info.getBingProperties();
            String namespace = properties.get("reportingNamespace");
            String url = properties.get("reportingURL");
            String userName = properties.get("username");
            String password = properties.get("password");
            String developerToken = properties.get("developerToken");
            String customerId = properties.get("customerId");
            String applicationToken = properties.get("applicationToken");
            int retries = Integer.parseInt(properties.get("retries"));

            Long wait = Long.parseLong(properties.get("waitForDownload"));


            for (String customerAccount: customerAccountArray){

                ReportingServiceLocator locator = new ReportingServiceLocator();
                locator.setBasicHttpBinding_IReportingServiceEndpointAddress(url);
                namespace = locator.getServiceName().getNamespaceURI();
                stub = (BasicHttpBinding_IReportingServiceStub) locator.getBasicHttpBinding_IReportingService();

                CustomReportRequest rr = new CustomReportRequest();

                stub.clearHeaders();

                stub.setHeader(namespace, "UserName", userName);
                stub.setHeader(namespace, "Password", password);
                stub.setHeader(namespace, "DeveloperToken", developerToken);
                stub.setHeader(namespace, "CustomerId", customerId);
                stub.setHeader(namespace, "CustomerAccountId", Long.parseLong(customerAccount));
                stub.setHeader(namespace, "ApplicationToken", applicationToken);


                rr.setStub(stub);

                AdGroupPerformanceReportRequest report = new AdGroupPerformanceReportRequest();

                report.setFormat(ReportFormat.Xml);

                report.setReportName("AdGroups performance report #" + date);
                report.setReturnOnlyCompleteData(false);
                report.setAggregation(ReportAggregation.Daily);


                report.setScope(new AccountThroughAdGroupReportScope());
                report.getScope().setAccountIds(new long[]{Long.parseLong(customerAccount)});
                report.getScope().setAdGroups(null);
                report.setTime(new ReportTime());



                String[] dateSplitted = date.split("-");


                report.getTime().setCustomDateRangeStart(new Date());
                report.getTime().getCustomDateRangeStart().setMonth(Integer.parseInt(dateSplitted[1]));
                report.getTime().getCustomDateRangeStart().setDay(Integer.parseInt(dateSplitted[2]));
                report.getTime().getCustomDateRangeStart().setYear(Integer.parseInt(dateSplitted[0]));
                report.getTime().setCustomDateRangeEnd(new Date());
                report.getTime().getCustomDateRangeEnd().setMonth(Integer.parseInt(dateSplitted[1]));
                report.getTime().getCustomDateRangeEnd().setDay(Integer.parseInt(dateSplitted[2]));
                report.getTime().getCustomDateRangeEnd().setYear(Integer.parseInt(dateSplitted[0]));



                report.setColumns(new AdGroupPerformanceReportColumn[] {
                        AdGroupPerformanceReportColumn.CampaignId,
                        AdGroupPerformanceReportColumn.AdGroupId,
                        AdGroupPerformanceReportColumn.Impressions,
                        AdGroupPerformanceReportColumn.Clicks,
                        AdGroupPerformanceReportColumn.Spend,
                        AdGroupPerformanceReportColumn.AveragePosition,
                        AdGroupPerformanceReportColumn.Conversions,
                        AdGroupPerformanceReportColumn.PhoneImpressions,
                        AdGroupPerformanceReportColumn.PhoneCalls,
                        AdGroupPerformanceReportColumn.ManualCalls,
                        AdGroupPerformanceReportColumn.ClickCalls

                });

                SubmitGenerateReportRequest request = new SubmitGenerateReportRequest();

                request.setReportRequest(report);

                String reportRequestId = stub.submitGenerateReport(request).getReportRequestId();

                rr.setReportRequestId(reportRequestId);

                requests.put(customerAccount, rr);


            }


            ReportRequestStatus reportRequestStatus = null;

            int finished = 0;

            for (int i = 0; i < retries && finished < requests.size(); i++)
            {

                try {Thread.sleep(wait);}
                catch (InterruptedException ignore) {}

                for(Map.Entry<String, CustomReportRequest> crr : requests.entrySet()){

                    //stub = crr.getValue().getStub();


                    PollGenerateReportRequest pollRequest = new PollGenerateReportRequest();

                    pollRequest.setReportRequestId(crr.getValue().getReportRequestId());

                    reportRequestStatus = stub.pollGenerateReport(pollRequest).getReportRequestStatus();

                    System.out.printf("Report Request Status: %s\n", reportRequestStatus);

                    if (reportRequestStatus.getStatus() == ReportRequestStatusType.Success ||
                            reportRequestStatus.getStatus() == ReportRequestStatusType.Error)
                    {
                        crr.getValue().setStatus(reportRequestStatus);
                        crr.getValue().setFinished(true);

                        //break;
                    }


                    if (crr.getValue().isFinished()){

                        if (crr.getValue().getStatus() != null)
                        {
                            if (crr.getValue().getStatus().getStatus() == ReportRequestStatusType.Success)
                            {
                                java.lang.String reportDownloadUrl = crr.getValue().getStatus().getReportDownloadUrl();

                                File locationDir = new File(location + File.separator + crr.getKey() + "-" + date);

                                if (!locationDir.exists())
                                    locationDir.mkdir();

                                System.out.printf("Downloading from %s.\n", reportDownloadUrl);
                                DownloadReport(reportDownloadUrl, location + File.separator + crr.getKey() + "-" + date + File.separator + "adGroupPerformanceReport_" + date + ".zip");
                                System.out.printf("The report was written to %s.\n", location + File.separator + crr.getKey() + "-" + date + File.separator + "adGroupPerformanceReport_" + date + ".zip");
                                finished++;
                            }
                            else if (reportRequestStatus.getStatus() == ReportRequestStatusType.Error)
                            {
                                System.out.println("The request failed. Try requesting the report " +
                                        "later.\nIf the request continues to fail, contact support.");
                            }
                            else  // Pending
                            {
                                System.out.println("The request is taking longer than expected.");
                                System.out.printf("Save the report ID (%s) and try again later.", crr.getValue().getReportRequestId());
                            }
                        }
                    }
                }
            }
        } catch (AdApiFaultDetail adApiFaultDetail) {
            adApiFaultDetail.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (RemoteException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (ServiceException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

    public void getAdPerformanceReport(String customerAccounts, String location, String date){
        BasicHttpBinding_IReportingServiceStub stub = null;

        HashMap<String, CustomReportRequest> requests = new HashMap<String, CustomReportRequest>();

        try{
            String[] customerAccountArray = customerAccounts.split(";");

            HashMap<String, String> properties = Info.getBingProperties();
            String namespace = properties.get("reportingNamespace");
            String url = properties.get("reportingURL");
            String userName = properties.get("username");
            String password = properties.get("password");
            String developerToken = properties.get("developerToken");
            String customerId = properties.get("customerId");
            String applicationToken = properties.get("applicationToken");
            int retries = Integer.parseInt(properties.get("retries"));

            Long wait = Long.parseLong(properties.get("waitForDownload"));


            for (String customerAccount: customerAccountArray){

                ReportingServiceLocator locator = new ReportingServiceLocator();
                locator.setBasicHttpBinding_IReportingServiceEndpointAddress(url);
                namespace = locator.getServiceName().getNamespaceURI();
                stub = (BasicHttpBinding_IReportingServiceStub) locator.getBasicHttpBinding_IReportingService();

                CustomReportRequest rr = new CustomReportRequest();

                stub.clearHeaders();

                stub.setHeader(namespace, "UserName", userName);
                stub.setHeader(namespace, "Password", password);
                stub.setHeader(namespace, "DeveloperToken", developerToken);
                stub.setHeader(namespace, "CustomerId", customerId);
                stub.setHeader(namespace, "CustomerAccountId", Long.parseLong(customerAccount));
                stub.setHeader(namespace, "ApplicationToken", applicationToken);


                rr.setStub(stub);

                AdPerformanceReportRequest report = new AdPerformanceReportRequest();

                report.setFormat(ReportFormat.Xml);

                report.setReportName("Ads performance report #" + date);
                report.setReturnOnlyCompleteData(false);
                report.setAggregation(NonHourlyReportAggregation.Daily);


                report.setScope(new AccountThroughAdGroupReportScope());
                report.getScope().setAccountIds(new long[]{Long.parseLong(customerAccount)});
                report.getScope().setAdGroups(null);
                report.setTime(new ReportTime());



                String[] dateSplitted = date.split("-");


                report.getTime().setCustomDateRangeStart(new Date());
                report.getTime().getCustomDateRangeStart().setMonth(Integer.parseInt(dateSplitted[1]));
                report.getTime().getCustomDateRangeStart().setDay(Integer.parseInt(dateSplitted[2]));
                report.getTime().getCustomDateRangeStart().setYear(Integer.parseInt(dateSplitted[0]));
                report.getTime().setCustomDateRangeEnd(new Date());
                report.getTime().getCustomDateRangeEnd().setMonth(Integer.parseInt(dateSplitted[1]));
                report.getTime().getCustomDateRangeEnd().setDay(Integer.parseInt(dateSplitted[2]));
                report.getTime().getCustomDateRangeEnd().setYear(Integer.parseInt(dateSplitted[0]));

                report.setColumns(new AdPerformanceReportColumn[] {
                        AdPerformanceReportColumn.AdId,
                        AdPerformanceReportColumn.AdGroupId,
                        AdPerformanceReportColumn.Impressions,
                        AdPerformanceReportColumn.Conversions,
                        AdPerformanceReportColumn.Clicks,
                        AdPerformanceReportColumn.Spend,
                        AdPerformanceReportColumn.AveragePosition,
                        AdPerformanceReportColumn.DeviceType,
                        AdPerformanceReportColumn.CampaignName
                });


                SubmitGenerateReportRequest request = new SubmitGenerateReportRequest();

                request.setReportRequest(report);

                String reportRequestId = stub.submitGenerateReport(request).getReportRequestId();

                rr.setReportRequestId(reportRequestId);

                requests.put(customerAccount, rr);


            }


            ReportRequestStatus reportRequestStatus = null;

            int finished = 0;

            for (int i = 0; i < retries && finished < requests.size(); i++)
            {

                try {Thread.sleep(wait);}
                catch (InterruptedException ignore) {}

                for(Map.Entry<String, CustomReportRequest> crr : requests.entrySet()){

                    //stub = crr.getValue().getStub();


                    PollGenerateReportRequest pollRequest = new PollGenerateReportRequest();

                    pollRequest.setReportRequestId(crr.getValue().getReportRequestId());

                    reportRequestStatus = stub.pollGenerateReport(pollRequest).getReportRequestStatus();

                    System.out.printf("Report Request Status: %s\n", reportRequestStatus);

                    if (reportRequestStatus.getStatus() == ReportRequestStatusType.Success ||
                            reportRequestStatus.getStatus() == ReportRequestStatusType.Error)
                    {
                        crr.getValue().setStatus(reportRequestStatus);
                        crr.getValue().setFinished(true);

                        //break;
                    }


                    if (crr.getValue().isFinished()){

                        if (crr.getValue().getStatus() != null)
                        {
                            if (crr.getValue().getStatus().getStatus() == ReportRequestStatusType.Success)
                            {
                                java.lang.String reportDownloadUrl = crr.getValue().getStatus().getReportDownloadUrl();

                                File locationDir = new File(location + File.separator + crr.getKey() + "-" + date);

                                if (!locationDir.exists())
                                    locationDir.mkdir();

                                System.out.printf("Downloading from %s.\n", reportDownloadUrl);
                                DownloadReport(reportDownloadUrl, location + File.separator  + crr.getKey() + "-" + date + File.separator + "adPerformanceReport_" + date + ".zip");
                                System.out.printf("The report was written to %s.\n", location + File.separator + crr.getKey() + "-" + date + File.separator + "adPerformanceReport_" + date + ".zip");
                                finished++;
                            }
                            else if (reportRequestStatus.getStatus() == ReportRequestStatusType.Error)
                            {
                                System.out.println("The request failed. Try requesting the report " +
                                        "later.\nIf the request continues to fail, contact support.");
                            }
                            else  // Pending
                            {
                                System.out.println("The request is taking longer than expected.");
                                System.out.printf("Save the report ID (%s) and try again later.", crr.getValue().getReportRequestId());
                            }
                        }
                    }
                }
            }
        } catch (AdApiFaultDetail adApiFaultDetail) {
            adApiFaultDetail.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (RemoteException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (ServiceException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

    }

    public void getAdExtensionPerformanceReport(String customerAccounts, String location, String date){
        BasicHttpBinding_IReportingServiceStub stub = null;

        HashMap<String, CustomReportRequest> requests = new HashMap<String, CustomReportRequest>();

        try{
            String[] customerAccountArray = customerAccounts.split(";");

            HashMap<String, String> properties = Info.getBingProperties();
            String namespace = properties.get("reportingNamespace");
            String url = properties.get("reportingURL");
            String userName = properties.get("username");
            String password = properties.get("password");
            String developerToken = properties.get("developerToken");
            String customerId = properties.get("customerId");
            String applicationToken = properties.get("applicationToken");
            int retries = Integer.parseInt(properties.get("retries"));

            Long wait = Long.parseLong(properties.get("waitForDownload"));


            for (String customerAccount: customerAccountArray){

                ReportingServiceLocator locator = new ReportingServiceLocator();
                locator.setBasicHttpBinding_IReportingServiceEndpointAddress(url);
                namespace = locator.getServiceName().getNamespaceURI();
                stub = (BasicHttpBinding_IReportingServiceStub) locator.getBasicHttpBinding_IReportingService();

                CustomReportRequest rr = new CustomReportRequest();

                stub.clearHeaders();

                stub.setHeader(namespace, "UserName", userName);
                stub.setHeader(namespace, "Password", password);
                stub.setHeader(namespace, "DeveloperToken", developerToken);
                stub.setHeader(namespace, "CustomerId", customerId);
                stub.setHeader(namespace, "CustomerAccountId", Long.parseLong(customerAccount));
                stub.setHeader(namespace, "ApplicationToken", applicationToken);


                rr.setStub(stub);

                AdExtensionByAdReportRequest report = new AdExtensionByAdReportRequest();

                report.setFormat(ReportFormat.Xml);

                report.setReportName("Ad Extensions performance report #" + date);
                report.setReturnOnlyCompleteData(false);
                report.setAggregation(ReportAggregation.Daily);


                report.setScope(new AccountThroughAdGroupReportScope());
                report.getScope().setAccountIds(new long[]{Long.parseLong(customerAccount)});
                report.getScope().setAdGroups(null);
                report.setTime(new ReportTime());



                String[] dateSplitted = date.split("-");


                report.getTime().setCustomDateRangeStart(new Date());
                report.getTime().getCustomDateRangeStart().setMonth(Integer.parseInt(dateSplitted[1]));
                report.getTime().getCustomDateRangeStart().setDay(Integer.parseInt(dateSplitted[2]));
                report.getTime().getCustomDateRangeStart().setYear(Integer.parseInt(dateSplitted[0]));
                report.getTime().setCustomDateRangeEnd(new Date());
                report.getTime().getCustomDateRangeEnd().setMonth(Integer.parseInt(dateSplitted[1]));
                report.getTime().getCustomDateRangeEnd().setDay(Integer.parseInt(dateSplitted[2]));
                report.getTime().getCustomDateRangeEnd().setYear(Integer.parseInt(dateSplitted[0]));

                report.setColumns(new AdExtensionByAdReportColumn[] {
                        AdExtensionByAdReportColumn.AccountNumber,
                        AdExtensionByAdReportColumn.AdId,
                        AdExtensionByAdReportColumn.AdGroupId,
                        AdExtensionByAdReportColumn.AccountId,
                        AdExtensionByAdReportColumn.AdExtensionId,
                        AdExtensionByAdReportColumn.AdTitle,
                        AdExtensionByAdReportColumn.AdExtensionType,
                        AdExtensionByAdReportColumn.AdExtensionVersion,
                        AdExtensionByAdReportColumn.Impressions,
                        AdExtensionByAdReportColumn.Clicks,
                        AdExtensionByAdReportColumn.Ctr,
                        AdExtensionByAdReportColumn.Spend,
                        AdExtensionByAdReportColumn.Conversions,
                        AdExtensionByAdReportColumn.ConversionRate,
                        AdExtensionByAdReportColumn.CampaignId,
                        AdExtensionByAdReportColumn.TimePeriod
                });


                SubmitGenerateReportRequest request = new SubmitGenerateReportRequest();

                request.setReportRequest(report);

                String reportRequestId = stub.submitGenerateReport(request).getReportRequestId();

                rr.setReportRequestId(reportRequestId);

                requests.put(customerAccount, rr);


            }


            ReportRequestStatus reportRequestStatus = null;

            int finished = 0;

            for (int i = 0; i < retries && finished < requests.size(); i++)
            {

                try {Thread.sleep(wait);}
                catch (InterruptedException ignore) {}

                for(Map.Entry<String, CustomReportRequest> crr : requests.entrySet()){

                    //stub = crr.getValue().getStub();


                    PollGenerateReportRequest pollRequest = new PollGenerateReportRequest();

                    pollRequest.setReportRequestId(crr.getValue().getReportRequestId());

                    reportRequestStatus = stub.pollGenerateReport(pollRequest).getReportRequestStatus();

                    System.out.printf("Report Request Status: %s\n", reportRequestStatus);

                    if (reportRequestStatus.getStatus() == ReportRequestStatusType.Success ||
                            reportRequestStatus.getStatus() == ReportRequestStatusType.Error)
                    {
                        crr.getValue().setStatus(reportRequestStatus);
                        crr.getValue().setFinished(true);

                        //break;
                    }


                    if (crr.getValue().isFinished()){

                        if (crr.getValue().getStatus() != null)
                        {
                            if (crr.getValue().getStatus().getStatus() == ReportRequestStatusType.Success)
                            {
                                java.lang.String reportDownloadUrl = crr.getValue().getStatus().getReportDownloadUrl();

                                File locationDir = new File(location + File.separator + crr.getKey() + "-" + date);

                                if (!locationDir.exists())
                                    locationDir.mkdir();

                                System.out.printf("Downloading from %s.\n", reportDownloadUrl);
                                DownloadReport(reportDownloadUrl, location + File.separator  + crr.getKey() + "-" + date + File.separator + "adExtensionPerformanceReport_" + date + ".zip");
                                System.out.printf("The report was written to %s.\n", location + File.separator + crr.getKey() + "-" + date + File.separator + "adExtensionPerformanceReport_" + date + ".zip");
                                finished++;
                            }
                            else if (reportRequestStatus.getStatus() == ReportRequestStatusType.Error)
                            {
                                System.out.println("The request failed. Try requesting the report " +
                                        "later.\nIf the request continues to fail, contact support.");
                            }
                            else  // Pending
                            {
                                System.out.println("The request is taking longer than expected.");
                                System.out.printf("Save the report ID (%s) and try again later.", crr.getValue().getReportRequestId());
                            }
                        }
                    }
                }
            }
        } catch (AdApiFaultDetail adApiFaultDetail) {
            adApiFaultDetail.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (RemoteException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (ServiceException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

    public void getConversionPerformanceReport(String customerAccounts, String location, String date){
        BasicHttpBinding_IReportingServiceStub stub = null;

        HashMap<String, CustomReportRequest> requests = new HashMap<String, CustomReportRequest>();

        try{
            String[] customerAccountArray = customerAccounts.split(";");

            HashMap<String, String> properties = Info.getBingProperties();
            String namespace = properties.get("reportingNamespace");
            String url = properties.get("reportingURL");
            String userName = properties.get("username");
            String password = properties.get("password");
            String developerToken = properties.get("developerToken");
            String customerId = properties.get("customerId");
            String applicationToken = properties.get("applicationToken");
            int retries = Integer.parseInt(properties.get("retries"));

            Long wait = Long.parseLong(properties.get("waitForDownload"));


            for (String customerAccount: customerAccountArray){

                ReportingServiceLocator locator = new ReportingServiceLocator();
                locator.setBasicHttpBinding_IReportingServiceEndpointAddress(url);
                namespace = locator.getServiceName().getNamespaceURI();
                stub = (BasicHttpBinding_IReportingServiceStub) locator.getBasicHttpBinding_IReportingService();

                CustomReportRequest rr = new CustomReportRequest();

                stub.clearHeaders();

                stub.setHeader(namespace, "UserName", userName);
                stub.setHeader(namespace, "Password", password);
                stub.setHeader(namespace, "DeveloperToken", developerToken);
                stub.setHeader(namespace, "CustomerId", customerId);
                stub.setHeader(namespace, "CustomerAccountId", Long.parseLong(customerAccount));
                stub.setHeader(namespace, "ApplicationToken", applicationToken);


                rr.setStub(stub);

                ConversionPerformanceReportRequest report = new ConversionPerformanceReportRequest();

                report.setFormat(ReportFormat.Xml);

                report.setReportName("Conversions performance report #" + date);
                report.setReturnOnlyCompleteData(false);
                report.setAggregation(NonHourlyReportAggregation.Daily);


                report.setScope(new AccountThroughAdGroupReportScope());
                report.getScope().setAccountIds(new long[]{Long.parseLong(customerAccount)});
                report.getScope().setAdGroups(null);
                report.setTime(new ReportTime());



                String[] dateSplitted = date.split("-");


                report.getTime().setCustomDateRangeStart(new Date());
                report.getTime().getCustomDateRangeStart().setMonth(Integer.parseInt(dateSplitted[1]));
                report.getTime().getCustomDateRangeStart().setDay(Integer.parseInt(dateSplitted[2]));
                report.getTime().getCustomDateRangeStart().setYear(Integer.parseInt(dateSplitted[0]));
                report.getTime().setCustomDateRangeEnd(new Date());
                report.getTime().getCustomDateRangeEnd().setMonth(Integer.parseInt(dateSplitted[1]));
                report.getTime().getCustomDateRangeEnd().setDay(Integer.parseInt(dateSplitted[2]));
                report.getTime().getCustomDateRangeEnd().setYear(Integer.parseInt(dateSplitted[0]));

                report.setColumns(new ConversionPerformanceReportColumn[] {
                        ConversionPerformanceReportColumn.AccountId,
                        ConversionPerformanceReportColumn.AccountNumber,
                        ConversionPerformanceReportColumn.AdGroupId,
                        ConversionPerformanceReportColumn.Assists,
                        ConversionPerformanceReportColumn.CampaignId,
                        ConversionPerformanceReportColumn.Clicks,
                        ConversionPerformanceReportColumn.ConversionRate,
                        ConversionPerformanceReportColumn.Conversions,
                        ConversionPerformanceReportColumn.CostPerAssist,
                        ConversionPerformanceReportColumn.CostPerConversion,
                        ConversionPerformanceReportColumn.Ctr,
                        ConversionPerformanceReportColumn.ExtendedCost,
                        ConversionPerformanceReportColumn.KeywordId,
                        ConversionPerformanceReportColumn.Impressions,
                        ConversionPerformanceReportColumn.ReturnOnAdSpend,
                        ConversionPerformanceReportColumn.Revenue,
                        ConversionPerformanceReportColumn.RevenuePerAssist,
                        ConversionPerformanceReportColumn.RevenuePerConversion,
                        ConversionPerformanceReportColumn.Spend,
                        ConversionPerformanceReportColumn.TimePeriod

                });

                SubmitGenerateReportRequest request = new SubmitGenerateReportRequest();

                request.setReportRequest(report);

                String reportRequestId = stub.submitGenerateReport(request).getReportRequestId();

                rr.setReportRequestId(reportRequestId);

                requests.put(customerAccount, rr);


            }


            ReportRequestStatus reportRequestStatus = null;

            int finished = 0;

            for (int i = 0; i < retries && finished < requests.size(); i++)
            {

                try {Thread.sleep(wait);}
                catch (InterruptedException ignore) {}

                for(Map.Entry<String, CustomReportRequest> crr : requests.entrySet()){

                    //stub = crr.getValue().getStub();


                    PollGenerateReportRequest pollRequest = new PollGenerateReportRequest();

                    pollRequest.setReportRequestId(crr.getValue().getReportRequestId());

                    reportRequestStatus = stub.pollGenerateReport(pollRequest).getReportRequestStatus();

                    System.out.printf("Report Request Status: %s\n", reportRequestStatus);

                    if (reportRequestStatus.getStatus() == ReportRequestStatusType.Success ||
                            reportRequestStatus.getStatus() == ReportRequestStatusType.Error)
                    {
                        crr.getValue().setStatus(reportRequestStatus);
                        crr.getValue().setFinished(true);

                        //break;
                    }


                    if (crr.getValue().isFinished()){

                        if (crr.getValue().getStatus() != null)
                        {
                            if (crr.getValue().getStatus().getStatus() == ReportRequestStatusType.Success)
                            {
                                java.lang.String reportDownloadUrl = crr.getValue().getStatus().getReportDownloadUrl();

                                File locationDir = new File(location + File.separator + crr.getKey() + "-" + date);

                                if (!locationDir.exists())
                                    locationDir.mkdir();

                                System.out.printf("Downloading from %s.\n", reportDownloadUrl);
                                DownloadReport(reportDownloadUrl, location +"\\" + crr.getKey() + "-" + date + "\\conversionPerformanceReport_" + date + ".zip");
                                System.out.printf("The report was written to %s.\n", location +"\\" + crr.getKey() + "-" + date+ "\\conversionPerformanceReport_" + date + ".zip");
                                finished++;
                            }
                            else if (reportRequestStatus.getStatus() == ReportRequestStatusType.Error)
                            {
                                System.out.println("The request failed. Try requesting the report " +
                                        "later.\nIf the request continues to fail, contact support.");
                            }
                            else  // Pending
                            {
                                System.out.println("The request is taking longer than expected.");
                                System.out.printf("Save the report ID (%s) and try again later.", crr.getValue().getReportRequestId());
                            }
                        }
                    }
                }
            }





        } catch (AdApiFaultDetail adApiFaultDetail) {
            adApiFaultDetail.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (RemoteException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (ServiceException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

    public void getCampaignPerformanceReport(Long customerAccountId, String locationFile, String date){

        /*IReportingService reportingService = null;
        ReportingServiceLocator reportingServiceLocator = null; */
        BasicHttpBinding_IReportingServiceStub stub = null;

        try
        {

            HashMap<String, String> properties = Info.getBingProperties();
            String namespace = properties.get("reportingNamespace");
            String url = properties.get("reportingURL");
            String userName = properties.get("username");
            String password = properties.get("password");
            String developerToken = properties.get("developerToken");
            String customerId = properties.get("customerId");
            String applicationToken = properties.get("applicationToken");

            Long wait = Long.parseLong(properties.get("waitForDownload"));



            ReportingServiceLocator locator = new ReportingServiceLocator();
            locator.setBasicHttpBinding_IReportingServiceEndpointAddress(url);
            namespace = locator.getServiceName().getNamespaceURI();
            stub = (BasicHttpBinding_IReportingServiceStub) locator.getBasicHttpBinding_IReportingService();

            stub.clearHeaders();

            stub.setHeader(namespace, "UserName", userName);
            stub.setHeader(namespace, "Password", password);
            stub.setHeader(namespace, "DeveloperToken", developerToken);
            stub.setHeader(namespace, "CustomerId", customerId);
            stub.setHeader(namespace, "CustomerAccountId", customerAccountId);
            stub.setHeader(namespace, "ApplicationToken", applicationToken);

            CampaignPerformanceReportRequest report = new CampaignPerformanceReportRequest();

            report.setFormat(ReportFormat.Xml);

            report.setReportName("Campaign performance report #" + date);
            report.setReturnOnlyCompleteData(false);
            report.setAggregation(ReportAggregation.Daily);


            report.setScope(new AccountThroughCampaignReportScope());
            report.getScope().setAccountIds(new long[]{customerAccountId});
            report.getScope().setCampaigns(null);
            report.setTime(new ReportTime());



            String[] dateSplitted = date.split("-");


            report.getTime().setCustomDateRangeStart(new Date());
            report.getTime().getCustomDateRangeStart().setMonth(Integer.parseInt(dateSplitted[1]));
            report.getTime().getCustomDateRangeStart().setDay(Integer.parseInt(dateSplitted[2]));
            report.getTime().getCustomDateRangeStart().setYear(Integer.parseInt(dateSplitted[0]));
            report.getTime().setCustomDateRangeEnd(new Date());
            report.getTime().getCustomDateRangeEnd().setMonth(Integer.parseInt(dateSplitted[1]));
            report.getTime().getCustomDateRangeEnd().setDay(Integer.parseInt(dateSplitted[2]));
            report.getTime().getCustomDateRangeEnd().setYear(Integer.parseInt(dateSplitted[0]));




            report.setColumns(new CampaignPerformanceReportColumn[]{
                    CampaignPerformanceReportColumn.AccountNumber,
                    //CampaignPerformanceReportColumn.AccountName,
                    //CampaignPerformanceReportColumn.AverageCpc,
                    //CampaignPerformanceReportColumn.AverageCpm,
                    CampaignPerformanceReportColumn.AveragePosition,
                    //CampaignPerformanceReportColumn.AverageCpp,
                    //CampaignPerformanceReportColumn.AdDistribution,
                    CampaignPerformanceReportColumn.CampaignId,
                    //CampaignPerformanceReportColumn.CampaignName,
                    CampaignPerformanceReportColumn.Clicks,
                    CampaignPerformanceReportColumn.ClickCalls,
                    CampaignPerformanceReportColumn.Conversions,
                    //CampaignPerformanceReportColumn.ConversionRate,
                    //CampaignPerformanceReportColumn.CostPerConversion,
                    CampaignPerformanceReportColumn.Ctr,
                    CampaignPerformanceReportColumn.CurrencyCode,
                    CampaignPerformanceReportColumn.DeviceType,
                    //CampaignPerformanceReportColumn.DeviceOS,
                    //CampaignPerformanceReportColumn.HistoricKeywordRelevance,
                    //CampaignPerformanceReportColumn.HistoricLandingPageRelevance,
                    //CampaignPerformanceReportColumn.HistoricQualityScore,
                    CampaignPerformanceReportColumn.Impressions,
                    //CampaignPerformanceReportColumn.ImpressionSharePercent,
                    //CampaignPerformanceReportColumn.KeywordRelevance,
                    //CampaignPerformanceReportColumn.LandingPageRelevance,
                    //CampaignPerformanceReportColumn.LandingPageUserExperience,
                    //CampaignPerformanceReportColumn.ManualCalls,
                    //CampaignPerformanceReportColumn.Network,
                    //CampaignPerformanceReportColumn.PhoneCalls,
                    //CampaignPerformanceReportColumn.PhoneImpressions,
                   //CampaignPerformanceReportColumn.PhoneSpend,
                    //CampaignPerformanceReportColumn.Ptr,
                    //CampaignPerformanceReportColumn.QualityScore,
                    CampaignPerformanceReportColumn.Spend,
                    CampaignPerformanceReportColumn.Status,
                    CampaignPerformanceReportColumn.TimePeriod,
                    //CampaignPerformanceReportColumn.TopVsOther,
                    //CampaignPerformanceReportColumn.TotalCostPhoneAndClicks



            });

            //report.setMaxRows(10000);


            SubmitGenerateReportRequest request = new SubmitGenerateReportRequest();

            request.setReportRequest(report);

            String reportRequestId = stub.submitGenerateReport(request).getReportRequestId();

            System.out.println("Report Request ID: " + reportRequestId + "\n");


            ReportRequestStatus reportRequestStatus = null;

            for (int i = 0; i < 10; i++)
            {
                try {Thread.sleep(wait);}
                catch (InterruptedException ignore) {}


                PollGenerateReportRequest pollRequest = new PollGenerateReportRequest();

                pollRequest.setReportRequestId(reportRequestId);

                reportRequestStatus = stub.pollGenerateReport(pollRequest).getReportRequestStatus();

                System.out.printf("Report Request Status: %s\n", reportRequestStatus);

                if (reportRequestStatus.getStatus() == ReportRequestStatusType.Success ||
                        reportRequestStatus.getStatus() == ReportRequestStatusType.Error)
                {
                    break;
                }
            }

            if (reportRequestStatus != null)
            {
                if (reportRequestStatus.getStatus() == ReportRequestStatusType.Success)
                {
                    java.lang.String reportDownloadUrl = reportRequestStatus.getReportDownloadUrl();
                    System.out.printf("Downloading from %s.\n", reportDownloadUrl);
                    DownloadReport(reportDownloadUrl, locationFile);
                    System.out.printf("The report was written to %s.\n", locationFile);
                }
                else if (reportRequestStatus.getStatus() == ReportRequestStatusType.Error)
                {
                    System.out.println("The request failed. Try requesting the report " +
                            "later.\nIf the request continues to fail, contact support.");
                }
                else  // Pending
                {
                    System.out.println("The request is taking longer than expected.");
                    System.out.printf("Save the report ID (%s) and try again later.", reportRequestId);
                }
            }




        } catch (AdApiFaultDetail adApiFaultDetail) {
            adApiFaultDetail.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (RemoteException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (ServiceException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

    }

    public void getAdGroupPerformanceReport(Long customerAccountId, String locationFile, String date){

        BasicHttpBinding_IReportingServiceStub stub = null;

        try{
            HashMap<String, String> properties = Info.getBingProperties();
            String namespace = properties.get("reportingNamespace");
            String url = properties.get("reportingURL");
            String userName = properties.get("username");
            String password = properties.get("password");
            String developerToken = properties.get("developerToken");
            String customerId = properties.get("customerId");
            String applicationToken = properties.get("applicationToken");

            Long wait = Long.parseLong(properties.get("waitForDownload"));

            ReportingServiceLocator locator = new ReportingServiceLocator();
            locator.setBasicHttpBinding_IReportingServiceEndpointAddress(url);
            namespace = locator.getServiceName().getNamespaceURI();
            stub = (BasicHttpBinding_IReportingServiceStub) locator.getBasicHttpBinding_IReportingService();

            stub.clearHeaders();

            stub.setHeader(namespace, "UserName", userName);
            stub.setHeader(namespace, "Password", password);
            stub.setHeader(namespace, "DeveloperToken", developerToken);
            stub.setHeader(namespace, "CustomerId", customerId);
            stub.setHeader(namespace, "CustomerAccountId", customerAccountId);
            stub.setHeader(namespace, "ApplicationToken", applicationToken);

            AdGroupPerformanceReportRequest report = new AdGroupPerformanceReportRequest();

            report.setFormat(ReportFormat.Xml);

            report.setReportName("AdGroups performance report #" + date);
            report.setReturnOnlyCompleteData(false);
            report.setAggregation(ReportAggregation.Daily);


            report.setScope(new AccountThroughAdGroupReportScope());
            report.getScope().setAccountIds(new long[]{customerAccountId});
            report.getScope().setAdGroups(null);
            report.setTime(new ReportTime());



            String[] dateSplitted = date.split("-");


            report.getTime().setCustomDateRangeStart(new Date());
            report.getTime().getCustomDateRangeStart().setMonth(Integer.parseInt(dateSplitted[1]));
            report.getTime().getCustomDateRangeStart().setDay(Integer.parseInt(dateSplitted[2]));
            report.getTime().getCustomDateRangeStart().setYear(Integer.parseInt(dateSplitted[0]));
            report.getTime().setCustomDateRangeEnd(new Date());
            report.getTime().getCustomDateRangeEnd().setMonth(Integer.parseInt(dateSplitted[1]));
            report.getTime().getCustomDateRangeEnd().setDay(Integer.parseInt(dateSplitted[2]));
            report.getTime().getCustomDateRangeEnd().setYear(Integer.parseInt(dateSplitted[0]));



            report.setColumns(new AdGroupPerformanceReportColumn[] {
                    AdGroupPerformanceReportColumn.AccountName,
                    AdGroupPerformanceReportColumn.AccountNumber,
                    AdGroupPerformanceReportColumn.TimePeriod,
                    AdGroupPerformanceReportColumn.Status,
                    AdGroupPerformanceReportColumn.CampaignName,
                    AdGroupPerformanceReportColumn.CampaignId,
                    AdGroupPerformanceReportColumn.AdGroupName,
                    AdGroupPerformanceReportColumn.AdGroupId,
                    AdGroupPerformanceReportColumn.CurrencyCode,
                    AdGroupPerformanceReportColumn.AdDistribution,
                    AdGroupPerformanceReportColumn.Impressions,
                    AdGroupPerformanceReportColumn.Clicks,
                    AdGroupPerformanceReportColumn.Ctr,
                    AdGroupPerformanceReportColumn.AverageCpc,
                    AdGroupPerformanceReportColumn.Spend,
                    AdGroupPerformanceReportColumn.AveragePosition,
                    AdGroupPerformanceReportColumn.Conversions,
                    AdGroupPerformanceReportColumn.ConversionRate,
                    AdGroupPerformanceReportColumn.CostPerConversion,
                    AdGroupPerformanceReportColumn.AverageCpm,
                    AdGroupPerformanceReportColumn.PricingModel,
                    AdGroupPerformanceReportColumn.DeviceType,
                    AdGroupPerformanceReportColumn.Language,
                    AdGroupPerformanceReportColumn.DeviceOS,
                    AdGroupPerformanceReportColumn.ImpressionSharePercent,
                    AdGroupPerformanceReportColumn.ImpressionLostToBudgetPercent,
                    AdGroupPerformanceReportColumn.ImpressionLostToRankPercent,
                    AdGroupPerformanceReportColumn.QualityScore,
                    AdGroupPerformanceReportColumn.KeywordRelevance,
                    AdGroupPerformanceReportColumn.LandingPageRelevance,
                    AdGroupPerformanceReportColumn.LandingPageUserExperience,
                    AdGroupPerformanceReportColumn.HistoricQualityScore,
                    AdGroupPerformanceReportColumn.HistoricKeywordRelevance,
                    AdGroupPerformanceReportColumn.HistoricLandingPageRelevance,
                    AdGroupPerformanceReportColumn.HistoricLandingPageUserExperience,
                    AdGroupPerformanceReportColumn.ImpressionLostToBidPercent,
                    AdGroupPerformanceReportColumn.ImpressionLostToLandingPageRelevancePercent,
                    AdGroupPerformanceReportColumn.ImpressionLostToKeywordRelevancePercent,
                    AdGroupPerformanceReportColumn.BusinessListingId,
                    AdGroupPerformanceReportColumn.BusinessListingName,
                    AdGroupPerformanceReportColumn.BusinessCategoryId,
                    AdGroupPerformanceReportColumn.BusinessCategoryName,
                    AdGroupPerformanceReportColumn.PhoneImpressions,
                    AdGroupPerformanceReportColumn.PhoneCalls,
                    AdGroupPerformanceReportColumn.ManualCalls,
                    AdGroupPerformanceReportColumn.ClickCalls,
                    AdGroupPerformanceReportColumn.Ptr,
                    AdGroupPerformanceReportColumn.PhoneSpend,
                    AdGroupPerformanceReportColumn.AverageCpp,
                    AdGroupPerformanceReportColumn.TotalCostPhoneAndClicks,
                    AdGroupPerformanceReportColumn.Network,
                    AdGroupPerformanceReportColumn.TopVsOther
            });


            //report.setMaxRows(10000);


            SubmitGenerateReportRequest request = new SubmitGenerateReportRequest();

            request.setReportRequest(report);

            String reportRequestId = stub.submitGenerateReport(request).getReportRequestId();

            System.out.println("Report Request ID: " + reportRequestId + "\n");

            ReportRequestStatus reportRequestStatus = null;

            for (int i = 0; i < 10; i++)
            {
                try {Thread.sleep(wait);}
                catch (InterruptedException ignore) {}


                PollGenerateReportRequest pollRequest = new PollGenerateReportRequest();

                pollRequest.setReportRequestId(reportRequestId);

                reportRequestStatus = stub.pollGenerateReport(pollRequest).getReportRequestStatus();

                System.out.printf("Report Request Status: %s\n", reportRequestStatus);

                if (reportRequestStatus.getStatus() == ReportRequestStatusType.Success ||
                        reportRequestStatus.getStatus() == ReportRequestStatusType.Error)
                {
                    break;
                }
            }

            if (reportRequestStatus != null)
            {
                if (reportRequestStatus.getStatus() == ReportRequestStatusType.Success)
                {
                    java.lang.String reportDownloadUrl = reportRequestStatus.getReportDownloadUrl();
                    System.out.printf("Downloading from %s.\n", reportDownloadUrl);
                    DownloadReport(reportDownloadUrl, locationFile);
                    System.out.printf("The report was written to %s.\n", locationFile);
                }
                else if (reportRequestStatus.getStatus() == ReportRequestStatusType.Error)
                {
                    System.out.println("The request failed. Try requesting the report " +
                            "later.\nIf the request continues to fail, contact support.");
                }
                else  // Pending
                {
                    System.out.println("The request is taking longer than expected.");
                    System.out.printf("Save the report ID (%s) and try again later.", reportRequestId);
                }
            }




        } catch (AdApiFaultDetail adApiFaultDetail) {
            adApiFaultDetail.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (RemoteException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (ServiceException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }


    }

    public void getAdPerformanceReport(Long customerAccountId, String locationFile, String date){
        IReportingService reportingService = null;
        ReportingServiceLocator reportingServiceLocator = null;
        BasicHttpBinding_IReportingServiceStub stub = null;

        try{
            HashMap<String, String> properties = Info.getBingProperties();
            String namespace = properties.get("reportingNamespace");
            String url = properties.get("reportingURL");
            String userName = properties.get("username");
            String password = properties.get("password");
            String developerToken = properties.get("developerToken");
            String customerId = properties.get("customerId");
            String applicationToken = properties.get("applicationToken");

            Long wait = Long.parseLong(properties.get("waitForDownload"));


            ReportingServiceLocator locator = new ReportingServiceLocator();
            locator.setBasicHttpBinding_IReportingServiceEndpointAddress(url);
            namespace = locator.getServiceName().getNamespaceURI();
            stub = (BasicHttpBinding_IReportingServiceStub) locator.getBasicHttpBinding_IReportingService();

            stub.clearHeaders();

            stub.setHeader(namespace, "UserName", userName);
            stub.setHeader(namespace, "Password", password);
            stub.setHeader(namespace, "DeveloperToken", developerToken);
            stub.setHeader(namespace, "CustomerId", customerId);
            stub.setHeader(namespace, "CustomerAccountId", customerAccountId);
            stub.setHeader(namespace, "ApplicationToken", applicationToken);

            AdPerformanceReportRequest report = new AdPerformanceReportRequest();

            report.setFormat(ReportFormat.Xml);

            report.setReportName("Ads performance report #" + date);
            report.setReturnOnlyCompleteData(false);
            report.setAggregation(NonHourlyReportAggregation.Daily);


            report.setScope(new AccountThroughAdGroupReportScope());
            report.getScope().setAccountIds(new long[]{customerAccountId});
            report.getScope().setAdGroups(null);
            report.setTime(new ReportTime());



            String[] dateSplitted = date.split("-");


            report.getTime().setCustomDateRangeStart(new Date());
            report.getTime().getCustomDateRangeStart().setMonth(Integer.parseInt(dateSplitted[1]));
            report.getTime().getCustomDateRangeStart().setDay(Integer.parseInt(dateSplitted[2]));
            report.getTime().getCustomDateRangeStart().setYear(Integer.parseInt(dateSplitted[0]));
            report.getTime().setCustomDateRangeEnd(new Date());
            report.getTime().getCustomDateRangeEnd().setMonth(Integer.parseInt(dateSplitted[1]));
            report.getTime().getCustomDateRangeEnd().setDay(Integer.parseInt(dateSplitted[2]));
            report.getTime().getCustomDateRangeEnd().setYear(Integer.parseInt(dateSplitted[0]));

            report.setColumns(new AdPerformanceReportColumn[] {
                    AdPerformanceReportColumn.AccountName,
                    AdPerformanceReportColumn.AccountNumber,
                    AdPerformanceReportColumn.CampaignName,
                    AdPerformanceReportColumn.AdGroupName,
                    AdPerformanceReportColumn.AdId,
                    AdPerformanceReportColumn.AdGroupId,
                    AdPerformanceReportColumn.AdTitle,
                    AdPerformanceReportColumn.AdDescription,
                    AdPerformanceReportColumn.AdType,
                    AdPerformanceReportColumn.CurrencyCode,
                    AdPerformanceReportColumn.AdDistribution,
                    AdPerformanceReportColumn.Impressions,
                    AdPerformanceReportColumn.Clicks,
                    AdPerformanceReportColumn.Ctr,
                    AdPerformanceReportColumn.AverageCpc,
                    AdPerformanceReportColumn.Spend,
                    AdPerformanceReportColumn.AveragePosition,
                    AdPerformanceReportColumn.Conversions,
                    AdPerformanceReportColumn.ConversionRate,
                    AdPerformanceReportColumn.CostPerConversion,
                    AdPerformanceReportColumn.AverageCpm,
                    AdPerformanceReportColumn.PricingModel,
                    AdPerformanceReportColumn.DestinationUrl,
                    AdPerformanceReportColumn.DeviceType,
                    AdPerformanceReportColumn.Language,
                    AdPerformanceReportColumn.DisplayUrl,
                    AdPerformanceReportColumn.BusinessListingId,
                    AdPerformanceReportColumn.BusinessListingName,
                    AdPerformanceReportColumn.BusinessCategoryId,
                    AdPerformanceReportColumn.BusinessCategoryName,
                    AdPerformanceReportColumn.AdStatus,
                    AdPerformanceReportColumn.Network,
                    AdPerformanceReportColumn.TopVsOther
            });


            //report.setMaxRows(10000);


            SubmitGenerateReportRequest request = new SubmitGenerateReportRequest();

            request.setReportRequest(report);

            String reportRequestId = stub.submitGenerateReport(request).getReportRequestId();

            System.out.println("Report Request ID: " + reportRequestId + "\n");

            ReportRequestStatus reportRequestStatus = null;

            for (int i = 0; i < 10; i++)
            {
                try {Thread.sleep(wait);}
                catch (InterruptedException ignore) {}


                PollGenerateReportRequest pollRequest = new PollGenerateReportRequest();

                pollRequest.setReportRequestId(reportRequestId);

                reportRequestStatus = stub.pollGenerateReport(pollRequest).getReportRequestStatus();

                System.out.printf("Report Request Status: %s\n", reportRequestStatus);

                if (reportRequestStatus.getStatus() == ReportRequestStatusType.Success ||
                        reportRequestStatus.getStatus() == ReportRequestStatusType.Error)
                {
                    break;
                }
            }

            if (reportRequestStatus != null)
            {
                if (reportRequestStatus.getStatus() == ReportRequestStatusType.Success)
                {
                    java.lang.String reportDownloadUrl = reportRequestStatus.getReportDownloadUrl();
                    System.out.printf("Downloading from %s.\n", reportDownloadUrl);
                    DownloadReport(reportDownloadUrl, locationFile);
                    System.out.printf("The report was written to %s.\n", locationFile);
                }
                else if (reportRequestStatus.getStatus() == ReportRequestStatusType.Error)
                {
                    System.out.println("The request failed. Try requesting the report " +
                            "later.\nIf the request continues to fail, contact support.");
                }
                else  // Pending
                {
                    System.out.println("The request is taking longer than expected.");
                    System.out.printf("Save the report ID (%s) and try again later.", reportRequestId);
                }
            }
        } catch (AdApiFaultDetail adApiFaultDetail) {
            adApiFaultDetail.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (RemoteException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (ServiceException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

    public void getAdExtensionPerformanceReport(Long customerAccountId, String locationFile, String date){
        BasicHttpBinding_IReportingServiceStub stub = null;

        try{
            HashMap<String, String> properties = Info.getBingProperties();
            String namespace = properties.get("reportingNamespace");
            String url = properties.get("reportingURL");
            String userName = properties.get("username");
            String password = properties.get("password");
            String developerToken = properties.get("developerToken");
            String customerId = properties.get("customerId");
            String applicationToken = properties.get("applicationToken");

            Long wait = Long.parseLong(properties.get("waitForDownload"));


            ReportingServiceLocator locator = new ReportingServiceLocator();
            locator.setBasicHttpBinding_IReportingServiceEndpointAddress(url);
            namespace = locator.getServiceName().getNamespaceURI();
            stub = (BasicHttpBinding_IReportingServiceStub) locator.getBasicHttpBinding_IReportingService();

            stub.clearHeaders();

            stub.setHeader(namespace, "UserName", userName);
            stub.setHeader(namespace, "Password", password);
            stub.setHeader(namespace, "DeveloperToken", developerToken);
            stub.setHeader(namespace, "CustomerId", customerId);
            stub.setHeader(namespace, "CustomerAccountId", customerAccountId);
            stub.setHeader(namespace, "ApplicationToken", applicationToken);

            AdExtensionByAdReportRequest report = new AdExtensionByAdReportRequest();

            report.setFormat(ReportFormat.Xml);

            report.setReportName("Ad Extensions performance report #" + date);
            report.setReturnOnlyCompleteData(false);
            report.setAggregation(ReportAggregation.Daily);


            report.setScope(new AccountThroughAdGroupReportScope());
            report.getScope().setAccountIds(new long[]{customerAccountId});
            report.getScope().setAdGroups(null);
            report.setTime(new ReportTime());




            String[] dateSplitted = date.split("-");


            report.getTime().setCustomDateRangeStart(new Date());
            report.getTime().getCustomDateRangeStart().setMonth(Integer.parseInt(dateSplitted[1]));
            report.getTime().getCustomDateRangeStart().setDay(Integer.parseInt(dateSplitted[2]));
            report.getTime().getCustomDateRangeStart().setYear(Integer.parseInt(dateSplitted[0]));
            report.getTime().setCustomDateRangeEnd(new Date());
            report.getTime().getCustomDateRangeEnd().setMonth(Integer.parseInt(dateSplitted[1]));
            report.getTime().getCustomDateRangeEnd().setDay(Integer.parseInt(dateSplitted[2]));
            report.getTime().getCustomDateRangeEnd().setYear(Integer.parseInt(dateSplitted[0]));

            report.setColumns(new AdExtensionByAdReportColumn[] {
                    AdExtensionByAdReportColumn.AccountName,
                    AdExtensionByAdReportColumn.AccountNumber,
                    AdExtensionByAdReportColumn.CampaignName,
                    AdExtensionByAdReportColumn.AdGroupName,
                    AdExtensionByAdReportColumn.AdId,
                    AdExtensionByAdReportColumn.AdGroupId,
                    AdExtensionByAdReportColumn.AdTitle,
                    AdExtensionByAdReportColumn.AccountId,
                    AdExtensionByAdReportColumn.AdExtensionId,
                    AdExtensionByAdReportColumn.AdExtensionType,
                    AdExtensionByAdReportColumn.AdExtensionVersion,
                    AdExtensionByAdReportColumn.Impressions,
                    AdExtensionByAdReportColumn.Clicks,
                    AdExtensionByAdReportColumn.Ctr,
                    AdExtensionByAdReportColumn.AverageCpc,
                    AdExtensionByAdReportColumn.Spend,
                    AdExtensionByAdReportColumn.Conversions,
                    AdExtensionByAdReportColumn.ConversionRate,
                    AdExtensionByAdReportColumn.CampaignId,
                    AdExtensionByAdReportColumn.ClickType,
                    AdExtensionByAdReportColumn.DeviceOS,
                    AdExtensionByAdReportColumn.DeviceType,
                    AdExtensionByAdReportColumn.TimePeriod
            });


            //report.setMaxRows(10000);


            SubmitGenerateReportRequest request = new SubmitGenerateReportRequest();

            request.setReportRequest(report);

            String reportRequestId = stub.submitGenerateReport(request).getReportRequestId();

            System.out.println("Report Request ID: " + reportRequestId + "\n");

            ReportRequestStatus reportRequestStatus = null;

            for (int i = 0; i < 10; i++)
            {
                try {Thread.sleep(wait);}
                catch (InterruptedException ignore) {}


                PollGenerateReportRequest pollRequest = new PollGenerateReportRequest();

                pollRequest.setReportRequestId(reportRequestId);

                reportRequestStatus = stub.pollGenerateReport(pollRequest).getReportRequestStatus();

                System.out.printf("Report Request Status: %s\n", reportRequestStatus);

                if (reportRequestStatus.getStatus() == ReportRequestStatusType.Success ||
                        reportRequestStatus.getStatus() == ReportRequestStatusType.Error)
                {
                    break;
                }
            }

            if (reportRequestStatus != null)
            {
                if (reportRequestStatus.getStatus() == ReportRequestStatusType.Success)
                {
                    java.lang.String reportDownloadUrl = reportRequestStatus.getReportDownloadUrl();
                    System.out.printf("Downloading from %s.\n", reportDownloadUrl);
                    DownloadReport(reportDownloadUrl, locationFile);
                    System.out.printf("The report was written to %s.\n", locationFile);
                }
                else if (reportRequestStatus.getStatus() == ReportRequestStatusType.Error)
                {
                    System.out.println("The request failed. Try requesting the report " +
                            "later.\nIf the request continues to fail, contact support.");
                }
                else  // Pending
                {
                    System.out.println("The request is taking longer than expected.");
                    System.out.printf("Save the report ID (%s) and try again later.", reportRequestId);
                }
            }




        } catch (AdApiFaultDetail adApiFaultDetail) {
            adApiFaultDetail.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (RemoteException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (ServiceException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }


    }

    public void getBudgetSummaryReport(Long customerAccountId, String locationFile, String date){
        BasicHttpBinding_IReportingServiceStub stub = null;

        try{
            HashMap<String, String> properties = Info.getBingProperties();
            String namespace = properties.get("reportingNamespace");
            String url = properties.get("reportingURL");
            String userName = properties.get("username");
            String password = properties.get("password");
            String developerToken = properties.get("developerToken");
            String customerId = properties.get("customerId");
            String applicationToken = properties.get("applicationToken");

            Long wait = Long.parseLong(properties.get("waitForDownload"));


            ReportingServiceLocator locator = new ReportingServiceLocator();
            locator.setBasicHttpBinding_IReportingServiceEndpointAddress(url);
            namespace = locator.getServiceName().getNamespaceURI();
            stub = (BasicHttpBinding_IReportingServiceStub) locator.getBasicHttpBinding_IReportingService();

            stub.clearHeaders();

            stub.setHeader(namespace, "UserName", userName);
            stub.setHeader(namespace, "Password", password);
            stub.setHeader(namespace, "DeveloperToken", developerToken);
            stub.setHeader(namespace, "CustomerId", customerId);
            stub.setHeader(namespace, "CustomerAccountId", customerAccountId);
            stub.setHeader(namespace, "ApplicationToken", applicationToken);

            BudgetSummaryReportRequest report = new BudgetSummaryReportRequest();

            report.setFormat(ReportFormat.Xml);

            report.setReportName("Budget summary report #" + date);
            report.setReturnOnlyCompleteData(false);

            report.setScope(new AccountThroughCampaignReportScope());
            report.getScope().setAccountIds(new long[]{customerAccountId});
            report.setTime(new BudgetSummaryReportTime());



            String[] dateSplitted = date.split("-");


            report.getTime().setCustomDateRangeStart(new Date());
            report.getTime().getCustomDateRangeStart().setMonth(Integer.parseInt(dateSplitted[1]));
            report.getTime().getCustomDateRangeStart().setDay(Integer.parseInt(dateSplitted[2]));
            report.getTime().getCustomDateRangeStart().setYear(Integer.parseInt(dateSplitted[0]));
            report.getTime().setCustomDateRangeEnd(new Date());
            report.getTime().getCustomDateRangeEnd().setMonth(Integer.parseInt(dateSplitted[1]));
            report.getTime().getCustomDateRangeEnd().setDay(Integer.parseInt(dateSplitted[2]));
            report.getTime().getCustomDateRangeEnd().setYear(Integer.parseInt(dateSplitted[0]));

            report.setColumns(new BudgetSummaryReportColumn[]{
                    BudgetSummaryReportColumn.AccountName,
                    BudgetSummaryReportColumn.AccountNumber,
                    BudgetSummaryReportColumn.CampaignName,
                    BudgetSummaryReportColumn.CurrencyCode,
                    BudgetSummaryReportColumn.DailySpend,
                    BudgetSummaryReportColumn.Date,
                    BudgetSummaryReportColumn.MonthlyBudget,
                    BudgetSummaryReportColumn.MonthToDateSpend
            });


            //report.setMaxRows(10000);


            SubmitGenerateReportRequest request = new SubmitGenerateReportRequest();

            request.setReportRequest(report);

            String reportRequestId = stub.submitGenerateReport(request).getReportRequestId();

            System.out.println("Report Request ID: " + reportRequestId + "\n");

            ReportRequestStatus reportRequestStatus = null;

            for (int i = 0; i < 10; i++)
            {
                try {Thread.sleep(wait);}
                catch (InterruptedException ignore) {}


                PollGenerateReportRequest pollRequest = new PollGenerateReportRequest();

                pollRequest.setReportRequestId(reportRequestId);

                reportRequestStatus = stub.pollGenerateReport(pollRequest).getReportRequestStatus();

                System.out.printf("Report Request Status: %s\n", reportRequestStatus);

                if (reportRequestStatus.getStatus() == ReportRequestStatusType.Success ||
                        reportRequestStatus.getStatus() == ReportRequestStatusType.Error)
                {
                    break;
                }
            }

            if (reportRequestStatus != null)
            {
                if (reportRequestStatus.getStatus() == ReportRequestStatusType.Success)
                {
                    java.lang.String reportDownloadUrl = reportRequestStatus.getReportDownloadUrl();
                    System.out.printf("Downloading from %s.\n", reportDownloadUrl);
                    DownloadReport(reportDownloadUrl, locationFile);
                    System.out.printf("The report was written to %s.\n", locationFile);
                }
                else if (reportRequestStatus.getStatus() == ReportRequestStatusType.Error)
                {
                    System.out.println("The request failed. Try requesting the report " +
                            "later.\nIf the request continues to fail, contact support.");
                }
                else  // Pending
                {
                    System.out.println("The request is taking longer than expected.");
                    System.out.printf("Save the report ID (%s) and try again later.", reportRequestId);
                }
            }

        } catch (AdApiFaultDetail adApiFaultDetail) {
            adApiFaultDetail.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (RemoteException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (ServiceException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

    public void getConversionPerformanceReport(Long customerAccountId, String locationFile, String date){
        BasicHttpBinding_IReportingServiceStub stub = null;

        try{
            HashMap<String, String> properties = Info.getBingProperties();
            String namespace = properties.get("reportingNamespace");
            String url = properties.get("reportingURL");
            String userName = properties.get("username");
            String password = properties.get("password");
            String developerToken = properties.get("developerToken");
            String customerId = properties.get("customerId");
            String applicationToken = properties.get("applicationToken");

            Long wait = Long.parseLong(properties.get("waitForDownload"));


            ReportingServiceLocator locator = new ReportingServiceLocator();
            locator.setBasicHttpBinding_IReportingServiceEndpointAddress(url);
            namespace = locator.getServiceName().getNamespaceURI();
            stub = (BasicHttpBinding_IReportingServiceStub) locator.getBasicHttpBinding_IReportingService();

            stub.clearHeaders();

            stub.setHeader(namespace, "UserName", userName);
            stub.setHeader(namespace, "Password", password);
            stub.setHeader(namespace, "DeveloperToken", developerToken);
            stub.setHeader(namespace, "CustomerId", customerId);
            stub.setHeader(namespace, "CustomerAccountId", customerAccountId);
            stub.setHeader(namespace, "ApplicationToken", applicationToken);

            ConversionPerformanceReportRequest report = new ConversionPerformanceReportRequest();

            report.setFormat(ReportFormat.Xml);

            report.setReportName("Conversions performance report #" + date);
            report.setReturnOnlyCompleteData(false);
            report.setAggregation(NonHourlyReportAggregation.Daily);


            report.setScope(new AccountThroughAdGroupReportScope());
            report.getScope().setAccountIds(new long[]{customerAccountId});
            report.getScope().setAdGroups(null);
            report.setTime(new ReportTime());



            String[] dateSplitted = date.split("-");


            report.getTime().setCustomDateRangeStart(new Date());
            report.getTime().getCustomDateRangeStart().setMonth(Integer.parseInt(dateSplitted[1]));
            report.getTime().getCustomDateRangeStart().setDay(Integer.parseInt(dateSplitted[2]));
            report.getTime().getCustomDateRangeStart().setYear(Integer.parseInt(dateSplitted[0]));
            report.getTime().setCustomDateRangeEnd(new Date());
            report.getTime().getCustomDateRangeEnd().setMonth(Integer.parseInt(dateSplitted[1]));
            report.getTime().getCustomDateRangeEnd().setDay(Integer.parseInt(dateSplitted[2]));
            report.getTime().getCustomDateRangeEnd().setYear(Integer.parseInt(dateSplitted[0]));

            report.setColumns(new ConversionPerformanceReportColumn[] {
                    ConversionPerformanceReportColumn.AccountId,
                    ConversionPerformanceReportColumn.AccountName,
                    ConversionPerformanceReportColumn.AccountNumber,
                    ConversionPerformanceReportColumn.AdGroupId,
                    ConversionPerformanceReportColumn.AdGroupName,
                    ConversionPerformanceReportColumn.Assists,
                    ConversionPerformanceReportColumn.CampaignId,
                    ConversionPerformanceReportColumn.CampaignName,
                    ConversionPerformanceReportColumn.Clicks,
                    ConversionPerformanceReportColumn.ConversionRate,
                    ConversionPerformanceReportColumn.Conversions,
                    ConversionPerformanceReportColumn.CostPerAssist,
                    ConversionPerformanceReportColumn.CostPerConversion,
                    ConversionPerformanceReportColumn.Ctr,
                    ConversionPerformanceReportColumn.DeviceType,
                    ConversionPerformanceReportColumn.ExtendedCost,
                    ConversionPerformanceReportColumn.Keyword,
                    ConversionPerformanceReportColumn.KeywordId,
                    ConversionPerformanceReportColumn.Impressions,
                    ConversionPerformanceReportColumn.ReturnOnAdSpend,
                    ConversionPerformanceReportColumn.Revenue,
                    ConversionPerformanceReportColumn.RevenuePerAssist,
                    ConversionPerformanceReportColumn.RevenuePerConversion,
                    ConversionPerformanceReportColumn.Spend,
                    ConversionPerformanceReportColumn.TimePeriod

            });


            SubmitGenerateReportRequest request = new SubmitGenerateReportRequest();

            request.setReportRequest(report);

            String reportRequestId = stub.submitGenerateReport(request).getReportRequestId();

            System.out.println("Report Request ID: " + reportRequestId + "\n");

            ReportRequestStatus reportRequestStatus = null;

            for (int i = 0; i < 10; i++)
            {
                try {Thread.sleep(wait);}
                catch (InterruptedException ignore) {}


                PollGenerateReportRequest pollRequest = new PollGenerateReportRequest();

                pollRequest.setReportRequestId(reportRequestId);

                reportRequestStatus = stub.pollGenerateReport(pollRequest).getReportRequestStatus();

                System.out.printf("Report Request Status: %s\n", reportRequestStatus);

                if (reportRequestStatus.getStatus() == ReportRequestStatusType.Success ||
                        reportRequestStatus.getStatus() == ReportRequestStatusType.Error)
                {
                    break;
                }
            }

            if (reportRequestStatus != null)
            {
                if (reportRequestStatus.getStatus() == ReportRequestStatusType.Success)
                {
                    java.lang.String reportDownloadUrl = reportRequestStatus.getReportDownloadUrl();
                    System.out.printf("Downloading from %s.\n", reportDownloadUrl);
                    DownloadReport(reportDownloadUrl, locationFile);
                    System.out.printf("The report was written to %s.\n", locationFile);
                }
                else if (reportRequestStatus.getStatus() == ReportRequestStatusType.Error)
                {
                    System.out.println("The request failed. Try requesting the report " +
                            "later.\nIf the request continues to fail, contact support.");
                }
                else  // Pending
                {
                    System.out.println("The request is taking longer than expected.");
                    System.out.printf("Save the report ID (%s) and try again later.", reportRequestId);
                }
            }
        } catch (AdApiFaultDetail adApiFaultDetail) {
            adApiFaultDetail.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (RemoteException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (ServiceException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

    public void getGoalsAndFunnelsReport(Long customerAccountId, String locationFile, String date){
        BasicHttpBinding_IReportingServiceStub stub = null;

        try{
            HashMap<String, String> properties = Info.getBingProperties();
            String namespace = properties.get("reportingNamespace");
            String url = properties.get("reportingURL");
            String userName = properties.get("username");
            String password = properties.get("password");
            String developerToken = properties.get("developerToken");
            String customerId = properties.get("customerId");
            String applicationToken = properties.get("applicationToken");

            Long wait = Long.parseLong(properties.get("waitForDownload"));


            ReportingServiceLocator locator = new ReportingServiceLocator();
            locator.setBasicHttpBinding_IReportingServiceEndpointAddress(url);
            namespace = locator.getServiceName().getNamespaceURI();
            stub = (BasicHttpBinding_IReportingServiceStub) locator.getBasicHttpBinding_IReportingService();

            stub.clearHeaders();

            stub.setHeader(namespace, "UserName", userName);
            stub.setHeader(namespace, "Password", password);
            stub.setHeader(namespace, "DeveloperToken", developerToken);
            stub.setHeader(namespace, "CustomerId", customerId);
            stub.setHeader(namespace, "CustomerAccountId", customerAccountId);
            stub.setHeader(namespace, "ApplicationToken", applicationToken);

            GoalsAndFunnelsReportRequest report = new GoalsAndFunnelsReportRequest();

            report.setFormat(ReportFormat.Xml);

            report.setReportName("Conversions performance report #" + date);
            report.setReturnOnlyCompleteData(false);
            report.setAggregation(NonHourlyReportAggregation.Daily);


            report.setScope(new AccountThroughAdGroupReportScope());
            report.getScope().setAccountIds(new long[]{customerAccountId});
            report.getScope().setAdGroups(null);
            report.setTime(new ReportTime());



            String[] dateSplitted = date.split("-");


            report.getTime().setCustomDateRangeStart(new Date());
            report.getTime().getCustomDateRangeStart().setMonth(Integer.parseInt(dateSplitted[1]));
            report.getTime().getCustomDateRangeStart().setDay(Integer.parseInt(dateSplitted[2]));
            report.getTime().getCustomDateRangeStart().setYear(Integer.parseInt(dateSplitted[0]));
            report.getTime().setCustomDateRangeEnd(new Date());
            report.getTime().getCustomDateRangeEnd().setMonth(Integer.parseInt(dateSplitted[1]));
            report.getTime().getCustomDateRangeEnd().setDay(Integer.parseInt(dateSplitted[2]));
            report.getTime().getCustomDateRangeEnd().setYear(Integer.parseInt(dateSplitted[0]));

            report.setColumns(new GoalsAndFunnelsReportColumn[] {
                    GoalsAndFunnelsReportColumn.AccountId,
                    GoalsAndFunnelsReportColumn.AccountName,
                    GoalsAndFunnelsReportColumn.AccountNumber,
                    GoalsAndFunnelsReportColumn.AdGroupId,
                    GoalsAndFunnelsReportColumn.AdGroupName,
                    GoalsAndFunnelsReportColumn.Assists,
                    GoalsAndFunnelsReportColumn.CampaignId,
                    GoalsAndFunnelsReportColumn.CampaignName,
                    GoalsAndFunnelsReportColumn.Conversions,
                    GoalsAndFunnelsReportColumn.ExtendedCost,
                    GoalsAndFunnelsReportColumn.FunnelConversionRate,
                    GoalsAndFunnelsReportColumn.Goal,
                    GoalsAndFunnelsReportColumn.Keyword,
                    GoalsAndFunnelsReportColumn.KeywordId,
                    GoalsAndFunnelsReportColumn.ReturnOnAdSpend,
                    GoalsAndFunnelsReportColumn.Revenue,
                    GoalsAndFunnelsReportColumn.Spend,
                    GoalsAndFunnelsReportColumn.Step1Count,
                    GoalsAndFunnelsReportColumn.Step2Count,
                    GoalsAndFunnelsReportColumn.Step3Count,
                    GoalsAndFunnelsReportColumn.Step4Count,
                    GoalsAndFunnelsReportColumn.Step5Count,
                    GoalsAndFunnelsReportColumn.TimePeriod
            });


            SubmitGenerateReportRequest request = new SubmitGenerateReportRequest();

            request.setReportRequest(report);

            String reportRequestId = stub.submitGenerateReport(request).getReportRequestId();

            System.out.println("Report Request ID: " + reportRequestId + "\n");

            ReportRequestStatus reportRequestStatus = null;

            for (int i = 0; i < 10; i++)
            {
                try {Thread.sleep(wait);}
                catch (InterruptedException ignore) {}


                PollGenerateReportRequest pollRequest = new PollGenerateReportRequest();

                pollRequest.setReportRequestId(reportRequestId);

                reportRequestStatus = stub.pollGenerateReport(pollRequest).getReportRequestStatus();

                System.out.printf("Report Request Status: %s\n", reportRequestStatus);

                if (reportRequestStatus.getStatus() == ReportRequestStatusType.Success ||
                        reportRequestStatus.getStatus() == ReportRequestStatusType.Error)
                {
                    break;
                }
            }

            if (reportRequestStatus != null)
            {
                if (reportRequestStatus.getStatus() == ReportRequestStatusType.Success)
                {
                    java.lang.String reportDownloadUrl = reportRequestStatus.getReportDownloadUrl();
                    System.out.printf("Downloading from %s.\n", reportDownloadUrl);
                    DownloadReport(reportDownloadUrl, locationFile);
                    System.out.printf("The report was written to %s.\n", locationFile);
                }
                else if (reportRequestStatus.getStatus() == ReportRequestStatusType.Error)
                {
                    System.out.println("The request failed. Try requesting the report " +
                            "later.\nIf the request continues to fail, contact support.");
                }
                else  // Pending
                {
                    System.out.println("The request is taking longer than expected.");
                    System.out.printf("Save the report ID (%s) and try again later.", reportRequestId);
                }
            }
        } catch (AdApiFaultDetail adApiFaultDetail) {
            adApiFaultDetail.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (RemoteException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (ServiceException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

    public void getSearchQueryPerformanceReport(Long customerAccountId, String locationFile, String date){
        BasicHttpBinding_IReportingServiceStub stub = null;

        try{
            HashMap<String, String> properties = Info.getBingProperties();
            String namespace = properties.get("reportingNamespace");
            String url = properties.get("reportingURL");
            String userName = properties.get("username");
            String password = properties.get("password");
            String developerToken = properties.get("developerToken");
            String customerId = properties.get("customerId");
            String applicationToken = properties.get("applicationToken");

            Long wait = Long.parseLong(properties.get("waitForDownload"));


            ReportingServiceLocator locator = new ReportingServiceLocator();
            locator.setBasicHttpBinding_IReportingServiceEndpointAddress(url);
            namespace = locator.getServiceName().getNamespaceURI();
            stub = (BasicHttpBinding_IReportingServiceStub) locator.getBasicHttpBinding_IReportingService();

            stub.clearHeaders();

            stub.setHeader(namespace, "UserName", userName);
            stub.setHeader(namespace, "Password", password);
            stub.setHeader(namespace, "DeveloperToken", developerToken);
            stub.setHeader(namespace, "CustomerId", customerId);
            stub.setHeader(namespace, "CustomerAccountId", customerAccountId);
            stub.setHeader(namespace, "ApplicationToken", applicationToken);

            SearchQueryPerformanceReportRequest report = new SearchQueryPerformanceReportRequest();

            report.setFormat(ReportFormat.Xml);

            report.setReportName("Conversions performance report #" + date);
            report.setReturnOnlyCompleteData(false);
            report.setAggregation(SearchQueryReportAggregation.Daily);


            report.setScope(new AccountThroughAdGroupReportScope());
            report.getScope().setAccountIds(new long[]{customerAccountId});
            report.getScope().setAdGroups(null);
            report.setTime(new ReportTime());




            String[] dateSplitted = date.split("-");


            report.getTime().setCustomDateRangeStart(new Date());
            report.getTime().getCustomDateRangeStart().setMonth(Integer.parseInt(dateSplitted[1]));
            report.getTime().getCustomDateRangeStart().setDay(Integer.parseInt(dateSplitted[2]));
            report.getTime().getCustomDateRangeStart().setYear(Integer.parseInt(dateSplitted[0]));
            report.getTime().setCustomDateRangeEnd(new Date());
            report.getTime().getCustomDateRangeEnd().setMonth(Integer.parseInt(dateSplitted[1]));
            report.getTime().getCustomDateRangeEnd().setDay(Integer.parseInt(dateSplitted[2]));
            report.getTime().getCustomDateRangeEnd().setYear(Integer.parseInt(dateSplitted[0]));

            report.setColumns(new SearchQueryPerformanceReportColumn[] {
                    SearchQueryPerformanceReportColumn.AccountId,
                    SearchQueryPerformanceReportColumn.AccountName,
                    SearchQueryPerformanceReportColumn.AccountNumber,
                    SearchQueryPerformanceReportColumn.AdGroupCriterionId,
                    SearchQueryPerformanceReportColumn.AdGroupId,
                    SearchQueryPerformanceReportColumn.AdGroupName,
                    SearchQueryPerformanceReportColumn.AdId,
                    SearchQueryPerformanceReportColumn.AdStatus,
                    SearchQueryPerformanceReportColumn.AdType,
                    SearchQueryPerformanceReportColumn.AverageCpc,
                    SearchQueryPerformanceReportColumn.AveragePosition,
                    SearchQueryPerformanceReportColumn.BidMatchType,
                    SearchQueryPerformanceReportColumn.CampaignId,
                    SearchQueryPerformanceReportColumn.CampaignName,
                    SearchQueryPerformanceReportColumn.CampaignStatus,
                    SearchQueryPerformanceReportColumn.Clicks,
                    SearchQueryPerformanceReportColumn.ConversionRate,
                    SearchQueryPerformanceReportColumn.Conversions,
                    SearchQueryPerformanceReportColumn.CostPerConversion,
                    SearchQueryPerformanceReportColumn.Ctr,
                    SearchQueryPerformanceReportColumn.DeliveredMatchType,
                    SearchQueryPerformanceReportColumn.DestinationUrl,
                    SearchQueryPerformanceReportColumn.Impressions,
                    SearchQueryPerformanceReportColumn.Keyword,
                    SearchQueryPerformanceReportColumn.KeywordId,
                    SearchQueryPerformanceReportColumn.Language,
                    SearchQueryPerformanceReportColumn.ProductTarget,
                    SearchQueryPerformanceReportColumn.SearchQuery,
                    SearchQueryPerformanceReportColumn.Spend,
                    SearchQueryPerformanceReportColumn.TimePeriod
            });


            SubmitGenerateReportRequest request = new SubmitGenerateReportRequest();

            request.setReportRequest(report);

            String reportRequestId = stub.submitGenerateReport(request).getReportRequestId();

            System.out.println("Report Request ID: " + reportRequestId + "\n");

            ReportRequestStatus reportRequestStatus = null;

            for (int i = 0; i < 10; i++)
            {
                try {Thread.sleep(wait);}
                catch (InterruptedException ignore) {}


                PollGenerateReportRequest pollRequest = new PollGenerateReportRequest();

                pollRequest.setReportRequestId(reportRequestId);

                reportRequestStatus = stub.pollGenerateReport(pollRequest).getReportRequestStatus();

                System.out.printf("Report Request Status: %s\n", reportRequestStatus);

                if (reportRequestStatus.getStatus() == ReportRequestStatusType.Success ||
                        reportRequestStatus.getStatus() == ReportRequestStatusType.Error)
                {
                    break;
                }
            }

            if (reportRequestStatus != null)
            {
                if (reportRequestStatus.getStatus() == ReportRequestStatusType.Success)
                {
                    java.lang.String reportDownloadUrl = reportRequestStatus.getReportDownloadUrl();
                    System.out.printf("Downloading from %s.\n", reportDownloadUrl);
                    DownloadReport(reportDownloadUrl, locationFile);
                    System.out.printf("The report was written to %s.\n", locationFile);
                }
                else if (reportRequestStatus.getStatus() == ReportRequestStatusType.Error)
                {
                    System.out.println("The request failed. Try requesting the report " +
                            "later.\nIf the request continues to fail, contact support.");
                }
                else  // Pending
                {
                    System.out.println("The request is taking longer than expected.");
                    System.out.printf("Save the report ID (%s) and try again later.", reportRequestId);
                }
            }
        } catch (AdApiFaultDetail adApiFaultDetail) {
            adApiFaultDetail.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (RemoteException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (ServiceException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

    public void getAccountPerformaceReport(String locationFile, String date){

        BasicHttpBinding_IReportingServiceStub stub = null;

        try{
            HashMap<String, String> properties = Info.getBingProperties();
            String namespace = properties.get("reportingNamespace");
            String url = properties.get("reportingURL");
            String userName = properties.get("username");
            String password = properties.get("password");
            String developerToken = properties.get("developerToken");
            String customerId = properties.get("customerId");
            String applicationToken = properties.get("applicationToken");

            Long wait = Long.parseLong(properties.get("waitForDownload"));


            ReportingServiceLocator locator = new ReportingServiceLocator();
            locator.setBasicHttpBinding_IReportingServiceEndpointAddress(url);
            namespace = locator.getServiceName().getNamespaceURI();
            stub = (BasicHttpBinding_IReportingServiceStub) locator.getBasicHttpBinding_IReportingService();

            stub.clearHeaders();

            stub.setHeader(namespace, "UserName", userName);
            stub.setHeader(namespace, "Password", password);
            stub.setHeader(namespace, "DeveloperToken", developerToken);
            stub.setHeader(namespace, "CustomerId", customerId);
            //stub.setHeader(namespace, "CustomerAccountId", customerAccountId);
            stub.setHeader(namespace, "ApplicationToken", applicationToken);

            AccountPerformanceReportRequest report = new AccountPerformanceReportRequest();

            report.setFormat(ReportFormat.Xml);

            report.setReportName("Ads performance report #" + date);
            report.setReturnOnlyCompleteData(false);
            report.setAggregation(ReportAggregation.Daily);


            report.setScope(new AccountReportScope());
            report.getScope().setAccountIds(null);
            //report.getScope().setAdGroups(null);
            report.setTime(new ReportTime());




            String[] dateSplitted = date.split("-");


            report.getTime().setCustomDateRangeStart(new Date());
            report.getTime().getCustomDateRangeStart().setMonth(Integer.parseInt(dateSplitted[1]));
            report.getTime().getCustomDateRangeStart().setDay(Integer.parseInt(dateSplitted[2]));
            report.getTime().getCustomDateRangeStart().setYear(Integer.parseInt(dateSplitted[0]));
            report.getTime().setCustomDateRangeEnd(new Date());
            report.getTime().getCustomDateRangeEnd().setMonth(Integer.parseInt(dateSplitted[1]));
            report.getTime().getCustomDateRangeEnd().setDay(Integer.parseInt(dateSplitted[2]));
            report.getTime().getCustomDateRangeEnd().setYear(Integer.parseInt(dateSplitted[0]));

            report.setColumns(new AccountPerformanceReportColumn[] {
                    AccountPerformanceReportColumn.AccountName,
                    AccountPerformanceReportColumn.AccountNumber,
                    AccountPerformanceReportColumn.AdDistribution,
                    AccountPerformanceReportColumn.AverageCpc,
                    AccountPerformanceReportColumn.AverageCpm,
                    AccountPerformanceReportColumn.AverageCpp,
                    AccountPerformanceReportColumn.AveragePosition,
                    AccountPerformanceReportColumn.ClickCalls,
                    AccountPerformanceReportColumn.Clicks,
                    AccountPerformanceReportColumn.ConversionRate,
                    AccountPerformanceReportColumn.Conversions,
                    AccountPerformanceReportColumn.CostPerConversion,
                    AccountPerformanceReportColumn.Ctr,
                    AccountPerformanceReportColumn.CurrencyCode,
                    AccountPerformanceReportColumn.DeviceOS,
                    AccountPerformanceReportColumn.DeviceType,
                    AccountPerformanceReportColumn.ImpressionLostToBidPercent,
                    AccountPerformanceReportColumn.ImpressionLostToBudgetPercent,
                    AccountPerformanceReportColumn.ImpressionLostToKeywordRelevancePercent,
                    AccountPerformanceReportColumn.ImpressionLostToLandingPageRelevancePercent,
                    AccountPerformanceReportColumn.ImpressionLostToRankPercent,
                    AccountPerformanceReportColumn.Impressions,
                    AccountPerformanceReportColumn.ImpressionSharePercent,
                    AccountPerformanceReportColumn.LowQualityClicks,
                    AccountPerformanceReportColumn.LowQualityClicksPercent,
                    AccountPerformanceReportColumn.LowQualityConversionRate,
                    AccountPerformanceReportColumn.LowQualityConversions,
                    AccountPerformanceReportColumn.LowQualityImpressions,
                    AccountPerformanceReportColumn.LowQualityImpressionsPercent,
                    AccountPerformanceReportColumn.ManualCalls,
                    AccountPerformanceReportColumn.Network,
                    AccountPerformanceReportColumn.PhoneCalls,
                    AccountPerformanceReportColumn.PhoneImpressions,
                    AccountPerformanceReportColumn.PhoneSpend,
                    AccountPerformanceReportColumn.Ptr,
                    AccountPerformanceReportColumn.Spend,
                    AccountPerformanceReportColumn.TimePeriod,
                    AccountPerformanceReportColumn.TopVsOther,
                    AccountPerformanceReportColumn.TotalCostPhoneAndClicks
            });


            //report.setMaxRows(10000);


            SubmitGenerateReportRequest request = new SubmitGenerateReportRequest();

            request.setReportRequest(report);

            String reportRequestId = stub.submitGenerateReport(request).getReportRequestId();

            System.out.println("Report Request ID: " + reportRequestId + "\n");

            ReportRequestStatus reportRequestStatus = null;

            for (int i = 0; i < 10; i++)
            {
                try {Thread.sleep(wait);}
                catch (InterruptedException ignore) {}


                PollGenerateReportRequest pollRequest = new PollGenerateReportRequest();

                pollRequest.setReportRequestId(reportRequestId);

                reportRequestStatus = stub.pollGenerateReport(pollRequest).getReportRequestStatus();

                System.out.printf("Report Request Status: %s\n", reportRequestStatus);

                if (reportRequestStatus.getStatus() == ReportRequestStatusType.Success ||
                        reportRequestStatus.getStatus() == ReportRequestStatusType.Error)
                {
                    break;
                }
            }

            if (reportRequestStatus != null)
            {
                if (reportRequestStatus.getStatus() == ReportRequestStatusType.Success)
                {
                    java.lang.String reportDownloadUrl = reportRequestStatus.getReportDownloadUrl();
                    System.out.printf("Downloading from %s.\n", reportDownloadUrl);
                    DownloadReport(reportDownloadUrl, locationFile);
                    System.out.printf("The report was written to %s.\n", locationFile);
                }
                else if (reportRequestStatus.getStatus() == ReportRequestStatusType.Error)
                {
                    System.out.println("The request failed. Try requesting the report " +
                            "later.\nIf the request continues to fail, contact support.");
                }
                else  // Pending
                {
                    System.out.println("The request is taking longer than expected.");
                    System.out.printf("Save the report ID (%s) and try again later.", reportRequestId);
                }
            }




        } catch (AdApiFaultDetail adApiFaultDetail) {
            adApiFaultDetail.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (RemoteException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (ServiceException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }



    }

    public void getSpendForClients(String clientIds, String locationFile, String startDate, String endDate, Long waitBetweenRequests){

        try{

            String[] clientIdsArray = clientIds.split(";");

            ArrayList<Thread> threads = new ArrayList<Thread>();

            for (String clientId : clientIdsArray){
                GetSpendForClient report = new GetSpendForClient(clientId, locationFile + File.separator + clientId + "_" + startDate + "_" + endDate + ".zip", startDate, endDate);
                report.start();
                threads.add(report);
                Thread.sleep(waitBetweenRequests);
            }


            for(Thread thread : threads){

                try {
                    thread.join();

                } catch (InterruptedException e) {
                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }

            }

        }catch (Exception e){
            e.printStackTrace();
        }

    }


    private void getSpendClient(String accountId, String locationFile, String startDate, String endDate){
        BasicHttpBinding_IReportingServiceStub stub = null;

        try{
            HashMap<String, String> properties = Info.getBingProperties();
            String namespace = properties.get("reportingNamespace");
            String url = properties.get("reportingURL");
            String userName = properties.get("username");
            String password = properties.get("password");
            String developerToken = properties.get("developerToken");
            String customerId = properties.get("customerId");
            String applicationToken = properties.get("applicationToken");

            Long wait = Long.parseLong(properties.get("waitForDownload"));


            ReportingServiceLocator locator = new ReportingServiceLocator();
            locator.setBasicHttpBinding_IReportingServiceEndpointAddress(url);
            namespace = locator.getServiceName().getNamespaceURI();
            stub = (BasicHttpBinding_IReportingServiceStub) locator.getBasicHttpBinding_IReportingService();

            stub.clearHeaders();

            stub.setHeader(namespace, "UserName", userName);
            stub.setHeader(namespace, "Password", password);
            stub.setHeader(namespace, "DeveloperToken", developerToken);
            stub.setHeader(namespace, "CustomerId", customerId);
            //stub.setHeader(namespace, "CustomerAccountId", customerAccountId);
            stub.setHeader(namespace, "ApplicationToken", applicationToken);

            AccountPerformanceReportRequest report = new AccountPerformanceReportRequest();

            report.setFormat(ReportFormat.Xml);

            report.setReportName("Account performance report #" + startDate + "_" + endDate);
            report.setReturnOnlyCompleteData(false);
            report.setAggregation(ReportAggregation.Daily);


            report.setScope(new AccountReportScope());
            report.getScope().setAccountIds(null);
            //report.getScope().setAdGroups(null);
            report.setTime(new ReportTime());




            String[] startDateSplitted = startDate.split("-");
            String[] endDateSplitted = endDate.split("-");


            report.getTime().setCustomDateRangeStart(new Date());
            report.getTime().getCustomDateRangeStart().setMonth(Integer.parseInt(startDateSplitted[1]));
            report.getTime().getCustomDateRangeStart().setDay(Integer.parseInt(startDateSplitted[2]));
            report.getTime().getCustomDateRangeStart().setYear(Integer.parseInt(startDateSplitted[0]));
            report.getTime().setCustomDateRangeEnd(new Date());
            report.getTime().getCustomDateRangeEnd().setMonth(Integer.parseInt(endDateSplitted[1]));
            report.getTime().getCustomDateRangeEnd().setDay(Integer.parseInt(endDateSplitted[2]));
            report.getTime().getCustomDateRangeEnd().setYear(Integer.parseInt(endDateSplitted[0]));

            report.setColumns(new AccountPerformanceReportColumn[] {
                    AccountPerformanceReportColumn.AccountNumber,
                    AccountPerformanceReportColumn.Spend
            });


            //report.setMaxRows(10000);


            SubmitGenerateReportRequest request = new SubmitGenerateReportRequest();

            request.setReportRequest(report);

            String reportRequestId = stub.submitGenerateReport(request).getReportRequestId();

            System.out.println("Report Request ID: " + reportRequestId + "\n");

            ReportRequestStatus reportRequestStatus = null;

            for (int i = 0; i < 10; i++)
            {
                try {Thread.sleep(wait);}
                catch (InterruptedException ignore) {}


                PollGenerateReportRequest pollRequest = new PollGenerateReportRequest();

                pollRequest.setReportRequestId(reportRequestId);

                reportRequestStatus = stub.pollGenerateReport(pollRequest).getReportRequestStatus();

                System.out.printf("Report Request Status: %s\n", reportRequestStatus);

                if (reportRequestStatus.getStatus() == ReportRequestStatusType.Success ||
                        reportRequestStatus.getStatus() == ReportRequestStatusType.Error)
                {
                    break;
                }
            }

            if (reportRequestStatus != null)
            {
                if (reportRequestStatus.getStatus() == ReportRequestStatusType.Success)
                {
                    java.lang.String reportDownloadUrl = reportRequestStatus.getReportDownloadUrl();
                    System.out.printf("Downloading from %s.\n", reportDownloadUrl);
                    DownloadReport(reportDownloadUrl, locationFile);
                    System.out.printf("The report was written to %s.\n", locationFile);
                }
                else if (reportRequestStatus.getStatus() == ReportRequestStatusType.Error)
                {
                    System.out.println("The request failed. Try requesting the report " +
                            "later.\nIf the request continues to fail, contact support.");
                }
                else  // Pending
                {
                    System.out.println("The request is taking longer than expected.");
                    System.out.printf("Save the report ID (%s) and try again later.", reportRequestId);
                }
            }




        } catch (AdApiFaultDetail adApiFaultDetail) {
            adApiFaultDetail.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (RemoteException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (ServiceException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

    public static java.lang.String DownloadReport(java.lang.String reportDownloadUrl, java.lang.String downloadPath) throws IOException
    {
        URL url = new URL(reportDownloadUrl);
        URLConnection request = null;
        int count = 0;
        BufferedInputStream reader = null;
        BufferedOutputStream writer = null;

        try
        {
            request = url.openConnection();

            reader = new BufferedInputStream(request.getInputStream());
            writer = new BufferedOutputStream(new FileOutputStream(downloadPath));

            final int bufferSize = 100 * 1024;
            byte[] buffer = new byte[bufferSize];

            while (-1 != (count = reader.read(buffer, 0, bufferSize)))
            {
                writer.write(buffer, 0, count);
            }
        }
        finally
        {
            reader.close();
            writer.flush();
            writer.close();
        }

        return downloadPath;
    }


}

class GetSpendForClient extends Thread{

    private String accountId;
    private String locationFile;
    private String startDate;
    private String endDate;

    GetSpendForClient(String accountId, String locationFile, String startDate, String endDate){
        this.accountId = accountId;
        this.locationFile = locationFile;
        this.startDate = startDate;
        this.endDate = endDate;
    }

    public void run(){

        BasicHttpBinding_IReportingServiceStub stub = null;

        try{
            HashMap<String, String> properties = Info.getBingProperties();
            String namespace = properties.get("reportingNamespace");
            String url = properties.get("reportingURL");
            String userName = properties.get("username");
            String password = properties.get("password");
            String developerToken = properties.get("developerToken");
            String customerId = properties.get("customerId");
            String applicationToken = properties.get("applicationToken");

            Long wait = Long.parseLong(properties.get("waitForDownload"));


            ReportingServiceLocator locator = new ReportingServiceLocator();
            locator.setBasicHttpBinding_IReportingServiceEndpointAddress(url);
            namespace = locator.getServiceName().getNamespaceURI();
            stub = (BasicHttpBinding_IReportingServiceStub) locator.getBasicHttpBinding_IReportingService();

            stub.clearHeaders();

            stub.setHeader(namespace, "UserName", userName);
            stub.setHeader(namespace, "Password", password);
            stub.setHeader(namespace, "DeveloperToken", developerToken);
            stub.setHeader(namespace, "CustomerId", customerId);
            //stub.setHeader(namespace, "CustomerAccountId", customerAccountId);
            stub.setHeader(namespace, "ApplicationToken", applicationToken);

            AccountPerformanceReportRequest report = new AccountPerformanceReportRequest();

            report.setFormat(ReportFormat.Xml);

            report.setReportName("Account performance report #" + startDate + "_" + endDate);
            report.setReturnOnlyCompleteData(false);
            report.setAggregation(ReportAggregation.Daily);


            report.setScope(new AccountReportScope());
            report.getScope().setAccountIds(new long[]{Long.parseLong(accountId)});
            //report.getScope().setAdGroups(null);
            report.setTime(new ReportTime());




            String[] startDateSplitted = startDate.split("-");
            String[] endDateSplitted = endDate.split("-");


            report.getTime().setCustomDateRangeStart(new Date());
            report.getTime().getCustomDateRangeStart().setMonth(Integer.parseInt(startDateSplitted[1]));
            report.getTime().getCustomDateRangeStart().setDay(Integer.parseInt(startDateSplitted[2]));
            report.getTime().getCustomDateRangeStart().setYear(Integer.parseInt(startDateSplitted[0]));
            report.getTime().setCustomDateRangeEnd(new Date());
            report.getTime().getCustomDateRangeEnd().setMonth(Integer.parseInt(endDateSplitted[1]));
            report.getTime().getCustomDateRangeEnd().setDay(Integer.parseInt(endDateSplitted[2]));
            report.getTime().getCustomDateRangeEnd().setYear(Integer.parseInt(endDateSplitted[0]));

            report.setColumns(new AccountPerformanceReportColumn[] {
                    AccountPerformanceReportColumn.AccountNumber,
                    AccountPerformanceReportColumn.Spend
            });


            //report.setMaxRows(10000);


            SubmitGenerateReportRequest request = new SubmitGenerateReportRequest();

            request.setReportRequest(report);

            String reportRequestId = stub.submitGenerateReport(request).getReportRequestId();

            System.out.println("Report Request ID: " + reportRequestId + "\n");

            ReportRequestStatus reportRequestStatus = null;

            for (int i = 0; i < 10; i++)
            {
                try {Thread.sleep(wait);}
                catch (InterruptedException ignore) {}


                PollGenerateReportRequest pollRequest = new PollGenerateReportRequest();

                pollRequest.setReportRequestId(reportRequestId);

                reportRequestStatus = stub.pollGenerateReport(pollRequest).getReportRequestStatus();

                System.out.printf("Report Request Status: %s\n", reportRequestStatus);

                if (reportRequestStatus.getStatus() == ReportRequestStatusType.Success ||
                        reportRequestStatus.getStatus() == ReportRequestStatusType.Error)
                {
                    break;
                }
            }

            if (reportRequestStatus != null)
            {
                if (reportRequestStatus.getStatus() == ReportRequestStatusType.Success)
                {
                    java.lang.String reportDownloadUrl = reportRequestStatus.getReportDownloadUrl();
                    System.out.printf("Downloading from %s.\n", reportDownloadUrl);
                    DownloadReport(reportDownloadUrl, locationFile);
                    System.out.printf("The report was written to %s.\n", locationFile);
                }
                else if (reportRequestStatus.getStatus() == ReportRequestStatusType.Error)
                {
                    System.out.println("The request failed. Try requesting the report " +
                            "later.\nIf the request continues to fail, contact support.");
                }
                else  // Pending
                {
                    System.out.println("The request is taking longer than expected.");
                    System.out.printf("Save the report ID (%s) and try again later.", reportRequestId);
                }
            }




        } catch (AdApiFaultDetail adApiFaultDetail) {
            adApiFaultDetail.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (RemoteException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (ServiceException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

    }

    public static java.lang.String DownloadReport(java.lang.String reportDownloadUrl, java.lang.String downloadPath) throws IOException
    {
        URL url = new URL(reportDownloadUrl);
        URLConnection request = null;
        int count = 0;
        BufferedInputStream reader = null;
        BufferedOutputStream writer = null;

        try
        {
            request = url.openConnection();

            reader = new BufferedInputStream(request.getInputStream());
            writer = new BufferedOutputStream(new FileOutputStream(downloadPath));

            final int bufferSize = 100 * 1024;
            byte[] buffer = new byte[bufferSize];

            while (-1 != (count = reader.read(buffer, 0, bufferSize)))
            {
                writer.write(buffer, 0, count);
            }
        }
        finally
        {
            reader.close();
            writer.flush();
            writer.close();
        }

        return downloadPath;
    }

}
